hdu 2645 bfs

思路:将所有‘1’的点入队bfs一次即可。

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <queue>
 5 using namespace std;
 6 
 7 typedef pair<int, int> pii;
 8 const int N = 183;
 9 char g[N][N];
10 int d[N][N];
11 int dx[] = { 0, 0, 1, -1 };
12 int dy[] = { 1, -1, 0, 0 };
13 int n, m;
14 
15 bool ok( int x, int y )
16 {
17     return x >= 0 && x < n && y >= 0 && y < m && d[x][y] == -1;
18 }
19 
20 queue<pii> q;
21 
22 void bfs()
23 {
24     memset( d, -1, sizeof(d) );
25     for ( int i = 0; i < n; i++ )
26     {
27         for ( int j = 0; j < m; j++ )
28         {
29             if ( g[i][j] == '1' )
30             {
31                 q.push( make_pair( i, j ) );
32                 d[i][j] = 0;
33             }
34         }
35     }
36     while ( !q.empty() )
37     {
38         pii cur = q.front();
39         q.pop();
40         for ( int i = 0; i < 4; i++ )
41         {
42             int x = cur.first + dx[i];
43             int y = cur.second + dy[i];
44             if ( ok( x, y ) )
45             {
46                 q.push( make_pair( x, y ) );
47                 d[x][y] = d[cur.first][cur.second] + 1;
48             }
49         }
50     }
51 }
52 
53 int main ()
54 {
55     while ( scanf("%d%d", &n, &m) != EOF )
56     {
57         for ( int i = 0; i < n; i++ )
58         {
59             scanf("%s", g[i]);
60         }
61         bfs();
62         for ( int i = 0; i < n; i++ )
63         {
64             for ( int j = 0; j < m; j++ )
65             {
66                 printf("%d", d[i][j]);
67                 if ( j != m - 1 ) putchar(' ');
68                 else putchar('\n');
69             }
70         }
71     }
72     return 0;
73 }

 

转载于:https://www.cnblogs.com/huoxiayu/p/4855705.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值