简单搜索

自从打了两天的比赛,自闭了,现在只能看看搜索,重新刷题了。

希望自己能在算法这个方面越走越远吧

一道简单的搜索题,(因为太累了,肝不动了,就水这个简单题吧)

题目的意思是:

如下面第一个图的九宫格中,放着 1~8 的数字卡片,还有一个格子空着。与空格子相邻的格子中的卡片可以移动到空格中。经过若干次移动,可以形成第二个图所示的局面。

  我们把第一个图的局面记为:12345678.
  把第二个图的局面记为:123.46758
  显然是按从上到下,从左到右的顺序记录数字,空格记为句点。
  本题目的任务是已知九宫的初态和终态,求最少经过多少步的移动可以到达。如果无论多少步都无法到达,则输出-1。

分析:

这个题就是一道简单bfs搜索题

注意坐标变换一下就行了

 1 #include <iostream>
 2 #include <queue>
 3 #include <map>
 4 using namespace std;
 5 
 6 map<string,bool> mp;
 7 int dx[4]={-1,0,1,0};
 8 int dy[4]={0,1,0,-1};
 9 
10 void swap(string& s,int pos1,int pos2){
11     char tem=s[pos1];
12     s[pos1]=s[pos2];
13     s[pos2]=tem;
14 }
15 
16 int main(){
17     string s1,s2;
18     cin>>s1;
19     cin>>s2;
20     int posd;
21     for(int i=0;i<s1.size();i++){
22         if(s1[i]=='.'){
23             posd=i;
24         }
25     }
26     mp[s1]=true;
27     queue<pair<pair<string,int>,int> > q;
28     q.push(make_pair(make_pair(s1,posd),0));
29     int stp=-1;
30     while(q.size()){
31         pair<pair<string,int>,int> t=q.front();
32         q.pop();
33         string nows=t.first.first;
34         int x=t.first.second/3;
35         int y=t.first.second%3;
36         if(nows==s2){
37             stp=t.second;
38             break;
39         }
40         for(int i=0;i<4;i++){
41             int xd=x+dx[i];
42             int yd=y+dy[i];
43             string nexs=nows;
44             if(xd>=0&&xd<3&&yd>=0&&yd<3){
45                 swap(nexs,t.first.second,xd*3+yd);
46                 if(mp[nexs]){
47                     continue;
48                 }
49                 q.push(make_pair(make_pair(nexs,xd*3+yd),t.second+1));
50                 mp[nexs]=true;
51             }
52         }
53     }
54     cout<<stp<<endl;
55 }

代码也好写,就不多说了,我好菜啊啊啊啊啊啊啊啊啊啊!

posted @ 2020-07-26 21:25  kstranger  阅读(172)  评论(0)    收藏  举报