洛谷1443-BFS

题目链接 https://www.luogu.org/problemnew/show/P1443

万物皆可搜。。。

这道题其实相当于象棋中的马,他可以走八个坐标,然后套用广搜模板,也是经典问题吧。。

 1 #include<iostream>
 2 #include<iomanip>
 3 #include<cstdio>
 4 #include<queue>
 5 using namespace std;
 6 int n,m,st,en;
 7 int mp[410][410];
 8 bool vis[410][410];
 9 struct node
10 {
11     int x;
12     int y;
13 };
14 queue<node> q;
15 int h[8][2]={{1,2},{-1,2},{-1,-2},{1,-2},{-2,1},{2,1},{2,-1},{-2,-1}};
16 void bfs(int s,int e)
17 {
18     node cnew;
19     cnew.x=s;
20     cnew.y=e;
21     vis[s][e]=1;
22     q.push(cnew);
23     while(!q.empty()){
24         node tnew;
25         tnew=q.front();
26         q.pop();
27         //cout<<tnew.x<<tnew.y<<endl;
28         for(int i=0;i<8;i++)
29         {
30             int tx=tnew.x+h[i][0];
31             int ty=tnew.y+h[i][1];
32             //cout<<tx<<' '<<ty<<endl;
33             if(tx<1||tx>n||ty<1||ty>m)
34                 continue;
35             else if(!vis[tx][ty]&&tx>=1&&tx<=n&&ty>=1&&ty<=m)
36             {
37                 mp[tx][ty]=mp[tnew.x][tnew.y]+1;
38                 vis[tx][ty]=1;
39                 node ttt;
40                 ttt.x=tx;
41                 ttt.y=ty;
42                 q.push(ttt);
43             }
44         }
45     }
46 }
47 int main()
48 {
49     cin>>n>>m>>st>>en;
50     for(int i=1;i<=n;i++)
51         for(int j=1;j<=m;j++)
52             mp[i][j]=-1;
53             mp[st][en]=0;
54             bfs(st,en);
55     for(int i=1;i<=n;i++)
56     {
57         for(int j=1;j<=m;j++)
58             cout<<left<<setw(5)<<mp[i][j];
59             cout<<endl;
60 }
61 }

 

posted @ 2019-05-02 20:28  liter_wave  阅读(110)  评论(0编辑  收藏  举报