Luo Gu P1379 eight digital problem (map)

Topic Portal

Problem-solving ideas:

A bfs, this question is the most difficult thing is how to store state has been visited, if directly open a bool array space will certainly be deep-fried, so we use another data structure stored, STL Dafa is good, with a map to save directly AC.

AC Code:

 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 }

 

Guess you like

Origin www.cnblogs.com/lipeiyi520/p/11348764.html