宽搜--knight moves hdu1372

写出来之后觉得是一道简单的宽搜题,但是之前写的时候遇到很多细节处理的小问题。刚刚开始,还需要更加努力。

首先是题目意思,骑士移动原来是走日字,智商捉急。

其次是方向处理问题,之前一直没转过弯。普遍方向表达有两种

第一种:

int h[8][2]={{-2,-1},{-2,1},{-1,2},{-1,-2},{1,-2},{1,2},{2,-1},{2,1}};
for(int i=0;i<8;i++){
            next.a=head.a+h[i][0];
            next.b=head.b+h[i][1];
}

  

第二种:

int x[8]={-2,-2,-1,-1,1,1,2,2};
int y[8]={-1,1,-2,2,2,-2,1,-1};
for(int i=0;i<8;i++){
           next.a=head.a+x[i];
           next.b=head.b+y[i];
}

  

  然后就是我经常会犯的错误,标记错误。一般是先初始化起点(包括起点步数清零,标记数组为false),然后在入队。这样不至于犯错。还有就是我总是会重命名,这个可得注意下次!!!

      最后就是到达不了终点怎么办,可写出有返回值的,没找到返回-1.(虽然这道题好像不需要考虑)。

好啦,最后附上代码

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<string.h>
 4 #include<algorithm>
 5 #include<queue>
 6 using namespace std;
 7 int h[8][2]={{-2,-1},{-2,1},{-1,2},{-1,-2},{1,-2},{1,2},{2,-1},{2,1}};
 8 bool vis[10][10];
 9 int step[10][10];
10 typedef struct knight{
11     int a,b;
12 }knight;
13 knight m,n;
14 int bfs_knight(knight t){
15     queue<knight>q;
16     knight head,next;
17     vis[t.a][t.b]=true;
18     step[t.a][t.b]=0;
19     q.push(t);
20     while(!q.empty()){
21         head=q.front();
22         q.pop();
23         for(int i=0;i<8;i++){
24             next.a=head.a+h[i][0];
25             next.b=head.b+h[i][1];
26             if((next.a>=1&&next.a<=8)&&(next.b>=1&&next.b<=8)&&!vis[next.a][next.b]){
27                 vis[next.a][next.b]=true;
28                 q.push(next);
29                 step[next.a][next.b]=step[head.a][head.b]+1;
30             }
31             if(next.a==n.a&&next.b==n.b){
32                 return step[next.a][next.b];
33             }
34         }
35     }
36     return -1;
37 }
38 int main(){
39     char s1[3],s2[3];
40     while(scanf("%s%s",s1,s2)!=EOF){
41         memset(vis,false,sizeof(vis));
42         memset(step,0,sizeof(step));
43         m.a=s1[0]-'a'+1;
44         n.a=s2[0]-'a'+1;
45         m.b=s1[1]-'0';
46         n.b=s2[1]-'0';
47         cout<<"To get from "<<s1<<" to "<<s2<<" takes "<<bfs_knight(m)<<" knight moves."<<endl;
48     }
49     return 0;
50 }

  

原文地址:https://www.cnblogs.com/wsyxy/p/4279492.html