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 }

 

posted @ 2015-10-05 14:27  hxy_has_been_used  阅读(140)  评论(0编辑  收藏  举报