bfs--P1443 马的遍历

有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步

 跟迷宫一样,找最近距离,显然用bfs,两个方位数组dir1和dir2用来表示马可以走的8个方向,循环判断八个方向,每次判断下一个位置是否越界或是否访问过,若都没有,则下一刻位置可走,并标记

完整代码:

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <cmath>
 5 #include <cstring>
 6 #include <queue>
 7 using namespace std;
 8 int n,m;
 9 int ex,ey;
10 int dirx[10]={1,1,-1,-1,2,2,-2,-2};
11 int diry[10]={2,-2,2,-2,1,-1,1,-1};
12 bool vis[500][500];
13 int a[500][500];
14 struct node{
15     int x,y,step;
16 }nowid,nextid;
17 inline int read()
18 {
19     int x = 1,a = 0;
20     char ch = getchar();
21     while(ch < '0' || ch > '9'){
22         if(ch == '-')x = -1;
23         ch = getchar();
24     }
25     while(ch <= '9'&&ch >= '0'){
26         a = a * 10 + ch - '0';
27         ch = getchar();
28     }
29     return x*a;
30 }
31 int k=0;
32 inline void bfs(int x,int y){
33     queue<node> q;
34     nowid.x=x,nowid.y=y,nowid.step=0;
35     q.push(nowid);
36     while (!q.empty()){
37         nowid=q.front();
38         q.pop();
39         nextid=nowid;
40         for (int i = 0;i < 8;i++){
41             nextid.x = nowid.x+dirx[i];
42             nextid.y = nowid.y+diry[i];
43             if (nextid.x<=n&&nextid.x>=1&&nextid.y<=m&&nextid.y>=1&&!vis[nextid.x][nextid.y]){
44                 nextid.step=nowid.step+1;
45                 vis[nextid.x][nextid.y]=1;
46                 a[nowid.x][nowid.y]=nowid.step;
47                 a[nextid.x][nextid.y]=nextid.step;
48                 q.push(nextid);
49             }
50         }
51     }
52 }
53 int main(){
54     n=read(),m=read();
55     ex=read(),ey=read();
56     vis[ex][ey]=1;
57     bfs(ex,ey);
58     for (int i = 1;i <= n;i++){
59         for (int j = 1;j <= m;j++){
60             if (vis[i][j])
61                 printf ("%-5d",a[i][j]);
62             else 
63                 printf ("%-5d",-1);    
64         }
65         cout<<endl;
66     }
67     return 0;
68 }

 

posted @ 2019-11-07 21:24  小又又  阅读(218)  评论(0编辑  收藏  举报