搜索--象棋中马的问题--hnust1497

 1 //没有考虑蹩脚的情况,这类问题可以看成约束的搜索问题----WA!
 2 //代码注意的地方:
 3     //1.Node结构体的设立,构造函数及对应新建对象的初始化,step放里面初始化为0?
 4     //2.bfs传入的是x和y,还是node?
 5     //3.只建立一个vis数组可行,即所有障碍点皆标记成访问过,或对整个地图的状态建立数组?
 6 #include<iostream>
 7 #include<queue>
 8 #include<cstring>
 9 #include<string>
10 
11 using namespace std;
12 
13 int n,p,q,m;
14 int sx,sy,ex,ey;
15 int cnt;
16 const int dir=8;
17 const int maxn=105;
18 int vis[maxn][maxn];
19 
20 struct Node 
21 {
22     int x,y,step;
23 };
24 
25 int dir_x[dir]={-2,-2,-1,-1,1,1,2,2};
26 int dir_y[dir]={-1,1,-2,2,-2,2,-1,1};
27 
28 
29 bool judge(int x,int y)
30 {
31     if(x<0||y<0||x>=p||y>=q||vis[x][y]==1)
32         return false;
33     else
34         return true;
35 }
36 
37 int bfs(int x,int y)
38 {
39     queue<Node> q;
40     Node stNode;
41     stNode.x=x;
42     stNode.y=y;
43     stNode.step=0;
44     q.push(stNode);
45     while(!q.empty())
46     {
47         Node top=q.front();
48         q.pop();
49         if(top.x==ex&&top.y==ey)
50             return top.step;
51         for(int i=0;i<dir;i++)
52         {
53             int newX=top.x+dir_x[i];
54             int newY=top.y+dir_y[i];
55             if(judge(newX,newY))
56             {
57                 Node temp;
58                 temp.x=newX;
59                 temp.y=newY;
60                 temp.step=top.step+1;
61                 q.push(temp);
62                 vis[newX][newY]=1;
63             }
64         }
65     }
66     return -1;
67 }
68 
69 
70 int main()
71 {
72     scanf("%d",&n);
73     while(n--)
74     {
75         memset(vis,0,sizeof(vis));
76         scanf("%d%d",&p,&q);
77         scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
78         scanf("%d",&m);
79         for(int i=0;i<m;i++)
80         {
81             Node temp;
82             scanf("%d%d",&temp.x,&temp.y);
83             vis[temp.x][temp.y]=1;
84         }
85         cnt=bfs(sx,sy);
86         if(cnt==-1)
87             printf("can not reach!\n");
88         else {
89             printf("%d\n",cnt);
90         }
91     }
92     return 0;
93 }

猜你喜欢

转载自www.cnblogs.com/chuanwen-tech/p/10287043.html
今日推荐