POJ 1915--Knight Moves

 1 //八个方向的BFS裸题---AC!
 2 //无需存图,注意结构体里未初始化的step值是如何改变的!
 3 #include<iostream>
 4 #include<queue>
 5 #include<cstring>
 6 
 7 using namespace std;
 8 
 9 int n,m,sx,sy,ex,ey,cnt;
10 const int maxn=305;
11 const int dirNum=8;
12 int vis[maxn][maxn];
13 
14 int dir_x[dirNum]={-2,-2,-1,-1,1,1,2,2};
15 int dir_y[dirNum]={-1,1,-2,2,-2,2,-1,1};
16 
17 bool judge(int x,int y)
18 {
19     if(x<0||y<0||x>=m||y>=m||vis[x][y]==1)
20         return false;
21     else
22         return true;
23 }
24 
25 struct Node
26 {
27     int x,y,step;
28 };
29 
30 int bfs(int x,int y)
31 {
32     Node node;
33     queue<Node> q;
34     node.x=x;
35     node.y=y;
36     node.step=0;
37     q.push(node);
38     while(!q.empty())
39     {
40         Node top=q.front();
41         q.pop();
42         if(top.x==ex&&top.y==ey)
43             return top.step;
44         for(int i=0;i<dirNum;++i)
45         {
46             int newX=top.x+dir_x[i];
47             int newY=top.y+dir_y[i];
48             if(judge(newX,newY))
49             {
50                 Node temp;
51                 temp.x=newX;
52                 temp.y=newY;
53                 temp.step=top.step+1;
54                 q.push(temp);
55                 vis[newX][newY]=1;
56             }
57         }
58     }
59 }
60 
61 int main()
62 {
63     cin>>n;
64     while(n--)
65     {
66         memset(vis,0,sizeof(vis));
67         cnt=0;
68         cin>>m;
69         cin>>sx>>sy>>ex>>ey;
70         if(sx==ex&&sy==ey)
71         {
72             cout<<0<<endl;
73             continue;
74         }
75         cnt=bfs(sx,sy);
76         cout<<cnt<<endl;
77 
78 
79     }
80     return 0;
81 }

猜你喜欢

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