题目传送门
解题思路:
一道bfs,本题最难的一点就是如何储存已经被访问过的状态,如果直接开一个bool数组,空间肯定会炸,所以我们要用另一个数据结构存,STL大法好,用map来存,直接AC.
AC代码:
1 #include<cstdio> 2 #include<iostream> 3 #include<map> 4 #include<queue> 5 6 using namespace std; 7 8 int a[3][3],n; 9 int ans = 123804765; 10 const int dx[]={-1,0,0,1},dy[]={0,-1,1,0}; 11 map<int,int> m; 12 13 inline void bfs() { 14 queue<long long> q; 15 q.push(n); 16 m[n] = 0; 17 while(!q.empty()) { 18 int u = q.front(); 19 q.pop(); 20 int x = 0,y= 0,n = u; 21 if(u == ans) break; 22 for(int i = 2;i >= 0; i--) 23 for(int j = 2;j >= 0; j--) { 24 a[i][j] = n % 10; 25 n /= 10; 26 if(!a[i][j]) x = i,y = j; 27 } 28 for(int i = 0;i < 4; i++) { 29 int nx = x + dx[i],ny = y + dy[i],ns = 0; 30 if(nx < 0 || ny < 0 || nx > 2 || ny > 2) continue; 31 swap(a[nx][ny],a[x][y]); 32 for(int i = 0;i <= 2; i++) 33 for(int j = 0;j <= 2; j++) 34 ns = ns * 10 + a[i][j]; 35 if(!m.count(ns)) { 36 m[ns] = m[u] + 1; 37 q.push(ns); 38 } 39 swap(a[nx][ny],a[x][y]); 40 } 41 } 42 } 43 44 int main() 45 { 46 scanf("%d",&n); 47 bfs(); 48 printf("%d",m[123804765]); 49 return 0; 50 }