zoukankan      html  css  js  c++  java
  • 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('
    ');
    69             }
    70         }
    71     }
    72     return 0;
    73 }
  • 相关阅读:
    codevs 1115 开心的金明
    POJ 1125 Stockbroker Grapevine
    POJ 2421 constructing roads
    codevs 1390 回文平方数 USACO
    codevs 1131 统计单词数 2011年NOIP全国联赛普及组
    codevs 1313 质因数分解
    洛谷 绕钉子的长绳子
    洛谷 P1276 校门外的树(增强版)
    codevs 2627 村村通
    codevs 1191 数轴染色
  • 原文地址:https://www.cnblogs.com/huoxiayu/p/4855705.html
Copyright © 2011-2022 走看看