#include <bits/stdc++.h> using namespace std;
const int INF = 987654321;
vector<pair<int, int>> cards[7]; int cardCount = 0; bool checkCard[7]; int dy[4] = {1, -1, 0, 0}; int dx[4] = {0, 0, 1, -1};
bool checkOrder[7]; vector<pair<int, int>> oneOrderCase; vector<vector<pair<int, int>>> allOrderCase; vector<vector<bool>> isDisappear;
int findCards(vector<vector<int>>& board) { int count = 0;
for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { int value = board[i][j];
if (value > 0) { cards[value].push_back({i, j}); count++; } } } return (count / 2); }
void findAllOrderCase(int depth) { if (depth == cardCount * 2) { allOrderCase.push_back(oneOrderCase); return; }
for (int i = 1; i < 7; i++) { if (cards[i].size() > 0 && checkOrder[i] == false) { pair<int, int> point1 = cards[i][0]; pair<int, int> point2 = cards[i][1];
checkOrder[i] = true;
oneOrderCase[depth] = point1; oneOrderCase[depth + 1] = point2; findAllOrderCase(depth + 2);
oneOrderCase[depth] = point2; oneOrderCase[depth + 1] = point1; findAllOrderCase(depth + 2);
checkOrder[i] = false; } } }
int bfs(vector<vector<int>>& board, pair<int, int> startPoint, pair<int, int> endPoint) { queue<pair<int, int>> q; q.push({startPoint.first, startPoint.second});
int count = 0; while (!q.empty()) { int q_size = q.size(); while (q_size--) { int cntY = q.front().first; int cntX = q.front().second; q.pop();
if (cntY == endPoint.first && cntX == endPoint.second) { if (board[startPoint.first][startPoint.second] == board[endPoint.first][endPoint.second]) { isDisappear[startPoint.first][startPoint.second] = true; isDisappear[endPoint.first][endPoint.second] = true; }
return count + 1; }
for (int i = 0; i < 4; i++) { int ny = cntY + dy[i]; int nx = cntX + dx[i];
if (0 > ny || ny >= 4 || 0 > nx || nx >= 4) { continue; } q.push({ny, nx});
while (0 <= (ny + dy[i]) && (ny + dy[i]) < 4 && 0 <= (nx + dx[i]) && (nx + dx[i]) < 4 && (board[ny][nx] == 0 || isDisappear[ny][nx] == true)) { ny += dy[i]; nx += dx[i]; } q.push({ny, nx}); } } count++; } return count; }
int solution(vector<vector<int>> board, int r, int c) { int answer = 0;
cardCount = findCards(board); oneOrderCase = vector<pair<int, int>>(cardCount * 2); findAllOrderCase(0);
int minDist = INF;
for (vector<pair<int, int>> points : allOrderCase) { isDisappear = vector<vector<bool>>(4, vector<bool>(4, false)); pair<int, int> startPoint = {r, c}; int cntDist = 0;
for (int i = 0; i < points.size(); i++) { pair<int, int> endPoint = points[i];
int value = bfs(board, startPoint, endPoint); cntDist += value; startPoint = endPoint; } minDist = min(minDist, cntDist); } answer = minDist;
return answer; }
|