Loading... 普通广搜 <!--more--> - 广搜,移动0的位置,并且用map去重,顺便map也记录一下最小步数。 - 采用long long保存一下状态,逐层深入,直到找到答案。 ```cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; int xc[4] = {1, -1, 0, 0}; int yc[4] = {0, 0, -1, 1}; struct Solution{ ll begin; map<ll, int> hash; void Solve(){ scanf("%lld", &begin); queue<ll> q; q.push(begin); while(!q.empty()){ int state = q.front(); q.pop(); if(state == 123804765) break; int a[3][3], x, y; for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ a[i][j] = (int)(state / (pow(10, 9 - (i * 3 + j + 1)))) % 10; if(!a[i][j]) x = i, y = j; } }//long long转矩阵 for(int i = 0; i < 4; i++){ int xn = x + xc[i], yn = y + yc[i]; if(xn > 2 || xn < 0 || yn > 2 || yn < 0) continue; swap(a[xn][yn], a[x][y]); ll now = 0; for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ now = now * 10 + a[i][j]; } }//矩阵转long long if(hash[now] == 0){ //如果没有保存过就压入队列 hash[now] = hash[state] + 1; q.push(now); } swap(a[xn][yn], a[x][y]); } } printf("%d", hash[123804765]); } }; int main(){ Solution().Solve(); return 0; } ``` Last modification:March 14, 2020 © Allow specification reprint Like 如果觉得我的文章对你有用,请随意赞赏