Skip to content

Create 773. Sliding Puzzle #643

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions 773. Sliding Puzzle
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
class Solution {
public:

pair<int, int>Finding_The_IndexOf_cell(vector<vector<int>>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<vector<int>>& board) {

int dx[4]{1, -1, 0, 0}, dy[4]{0, 0, 1, -1}; // 4 neighbours cells
map<vector<vector<int>> ,int>vis;
queue<vector<vector<int>>>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;
}
};
Loading