八数码问题(蒟蒻打卡)

原题:AcWing 845. 八数码 - AcWing

思路:用string储存状态bfs爆搜

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int bfs(string start)
 4 {
 5     int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};
 6     string end="12345678x";
 7     queue<string> q;
 8     unordered_map<string,int> d;
 9     q.push(start);
10     d[start]=0;
11     while(q.size())
12     {
13       
14         string t=q.front();q.pop();
15         if(t==end) return d[t];
16         int distance = d[t];
17         int k=t.find('x');
18         int x=k/3,y=k%3;
19         for(int i=0;i<4;i++)
20         {
21             int a=x+dx[i],b=y+dy[i];
22             if(a>=0 && a<3 && b>=0 && b<3)
23             {
24                 swap(t[k],t[a*3+b]);
25                 if(!d.count(t))
26                 {
27                     d[t]=distance+1;
28                     q.push(t);
29                 }
30                 swap(t[k],t[a*3+b]);
31             }
32         }
33     }
34     return -1;
35 }
36 int main()
37 {
38     char c;string start;
39     for(int i=0;i<9;i++)
40     {
41         cin>>c;
42         start+=c;
43     }
44     cout<<bfs(start)<<endl;
45     return 0;
46 }

 

posted @ 2023-04-25 20:12  喜欢网络冲浪の小蒜头  阅读(26)  评论(0)    收藏  举报