【日常水题-bfs】马的遍历

这几天日常一搜索qaq

 P1443 马的遍历

 1 #include<cstdio>
 2 #include<iostream>
 3 using namespace std;
 4 const int sz = 410;
 5 int n, m, sx, sy;
 6 int plat[sz][sz], q[sz*100][3];
 7 bool book[sz][sz];
 8 int dx[8] = {-2,-1,1,2,2,1,-1,-2},
 9     dy[8] = {1,2,2,1,-1,-2,-2,-1};
10 void bfs(int x, int y) {
11     int head = 1, tail = 1, mx, my;
12     plat[x][y] = 0;
13     book[x][y] = 1;
14     q[1][1] = x, q[1][2] = y;
15     while(head <= tail) {
16         int step = plat[q[head][1]][q[head][2]]+1;
17         for(int i = 0; i < 8; i++) {
18             mx = q[head][1] + dx[i];
19             my = q[head][2] + dy[i];
20             if(mx>=1&&my>=1&&mx<=n&&my<=m&&(!book[mx][my])) {
21                 tail++;
22                 plat[mx][my] = step;
23                 book[mx][my] = 1;
24                 q[tail][1] = mx;
25                 q[tail][2] = my;
26             }
27         }
28         head++;
29     }
30     
31 }
32 int print() {
33     for(int i = 1; i <= n; i++) {
34         for(int j = 1; j <= m; j++) {
35             if(plat[i][j] == 0 ) {
36                 if(i==sx&&j==sy) plat[i][j] = 0;
37                 else plat[i][j] = -1;
38             }
39             printf("%-5d", plat[i][j]);
40         }
41         cout<<endl;
42     }
43 }
44 int main() {
45     scanf("%d%d%d%d",&n,&m,&sx,&sy);
46     bfs(sx, sy);
47     print();
48     return 0;
49 }

十分朴素详实的bfs

感觉bfs全长一个样子QAQ

转载于:https://www.cnblogs.com/Hwjia/p/9704931.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值