diff --git a/773. Sliding Puzzle b/773. Sliding Puzzle new file mode 100644 index 0000000..e200e7c --- /dev/null +++ b/773. Sliding Puzzle @@ -0,0 +1,55 @@ +class Solution { +public: + + pairFinding_The_IndexOf_cell(vector>board){ + int x,y; + for(int i = 0; i < 2 ;i++) + for(int j = 0;j < 3; j++) + if(!board[i][j])x = i, y = j; + + return {x, y}; + } + + int slidingPuzzle(vector>& board) { + + int dx[4]{1, -1, 0, 0}, dy[4]{0, 0, 1, -1}; // 4 neighbours cells + map> ,int>vis; + queue>>q; + q.push(board); + + //BFS + while(q.size()){ + auto cur_board = q.front(); q.pop(); + + if(cur_board[0][0] == 1 && // Wining Case + cur_board[0][1] == 2 && + cur_board[0][2] == 3 && + cur_board[1][0] == 4 && + cur_board[1][1] == 5 && + !cur_board[1][2]){ + return vis[cur_board]; + } + + auto last_board = cur_board; + auto [x,y] = Finding_The_IndexOf_cell(cur_board); + + for(int i = 0;i < 4; i++){ // Try 4 neighbours cells + int x2 = x + dx[i] , y2 = y + dy[i]; + + if(x2 >= 0 && x2 < 2 && y2 >= 0 && y2 < 3){ + swap(cur_board[x][y], cur_board[x2][y2]); //Do + + if(!vis.count(cur_board)){ + vis[cur_board] = vis[last_board] + 1, + q.push(cur_board); + } + + swap(cur_board[x][y], cur_board[x2][y2]); + //(backtracking) + } + } + } + + return -1; + } +};