马的遍历(BFS

 

https://www.luogu.org/problemnew/show/P1443

模板BFS......

 

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<cmath>
 6 #include<string>
 7 #include<cmath>
 8 #include<set>
 9 #include<vector>
10 #include<stack>
11 #include<queue>
12 #include<map>
13 using namespace std;
14 #define ll long long
15 #define se second
16 #define fi first
17 const int INF= 0x3f3f3f3f;
18 const int N=1e5+5;
19 
20 int n,m,a,b;
21 int dx[8]={2,2,1,1,-2,-2,-1,-1},dy[8]={1,-1,2,-2,1,-1,2,-2};
22 int step[405][405];
23 bool vis[405][405];
24 
25 struct note
26 {
27     int x,y;
28     int s;
29 }w,p;
30 
31 queue<note>q;
32 
33 void bfs(int ax,int ay)
34 {
35     w.x=ax; w.y=ay; w.s=0;
36     vis[w.x][w.y]=1;
37     step[w.x][w.y]=w.s;
38 
39     q.push(w);
40     while( !q.empty())
41     {
42         p=q.front();
43         q.pop();
44         for(int i=0;i<8;i++)
45         {
46             w.x=p.x+dx[i];
47             w.y=p.y+dy[i];
48             if(w.x<=n&&w.x>=1&&w.y<=m&&w.y>=1&&vis[w.x][w.y]==0)
49             {
50                 vis[w.x][w.y]=1;
51                 w.s=p.s+1;
52                 step[w.x][w.y]=w.s;
53                 q.push(w);
54             }
55         }
56     }
57 }
58 
59 int main()
60 {
61     cin>>n>>m>>a>>b;
62     memset(step,-1,sizeof(step));
63     bfs(a,b);
64     for(int i=1;i<=n;i++){
65         for(int j=1;j<=m;j++)
66             printf("%-5d",step[i][j]);
67         cout<<endl;
68     }
69 }

 

posted @ 2018-07-16 12:45  木流牛马  阅读(157)  评论(0编辑  收藏  举报