zoukankan      html  css  js  c++  java
  • 【BFS】bzoj2252 [2010Beijing wc]矩阵距离

    要注意一开始将所有为'1'的点入队,然后通过一次BFS去更新所有点的距离,直到无法更新为止。

     1 #include<cstdio>
     2 #include<queue>
     3 #include<cstring>
     4 using namespace std;
     5 const int dx[]={0,0,-1,1},dy[]={1,-1,0,0};
     6 struct Point{int x,y;Point(const int &a,const int &b){x=a;y=b;}Point(){}};
     7 queue<Point>q;
     8 int n,m,d[1000][1000],num;
     9 char s[1000][1000],CH[20];
    10 inline void putint(int x)
    11 {
    12     num=0;  
    13     while(x>0){CH[++num]=x%10;x/=10;}
    14     while(num)putchar(CH[num--]+48);
    15     putchar(' ');
    16 }
    17 int main()
    18 {
    19     scanf("%d%d",&n,&m);
    20     memset(d,0x7f,sizeof(d));
    21     for(int i=0;i<n;i++)
    22       {
    23           scanf("%s",s[i]);
    24           for(int j=0;j<m;j++)
    25             if(s[i][j]=='1')
    26               {
    27                 d[i][j]=0;
    28                 q.push(Point(i,j));
    29               }
    30       }
    31     while(!q.empty())
    32       {
    33           for(int i=0;i<4;i++)
    34             {
    35                 int tx=dx[i]+q.front().x,ty=dy[i]+q.front().y;
    36                 if(tx>=0&&tx<n&&ty>=0&&ty<m&&d[q.front().x][q.front().y]+1<d[tx][ty])
    37                   {
    38                       q.push(Point(tx,ty));
    39                       d[tx][ty]=d[q.front().x][q.front().y]+1;
    40                   }
    41             }
    42           q.pop();
    43       }
    44     for(int i=0;i<n;i++)
    45       {
    46           for(int j=0;j<m;j++)
    47             if(d[i][j])putint(d[i][j]);
    48             else {putchar('0');putchar(' ');}
    49           putchar('
    ');
    50       }
    51     return 0;
    52 }
    ——The Solution By AutSky_JadeK From UESTC 转载请注明出处:http://www.cnblogs.com/autsky-jadek/
  • 相关阅读:
    问题账户需求分析
    2017年秋季个人阅读计划
    阅读笔记01
    个人总结
    第二阶段站立会议07
    第二阶段站立会议06
    第二阶段站立会议05
    第二阶段站立会议04
    第二阶段站立会议03
    学习进度条(第十五周)
  • 原文地址:https://www.cnblogs.com/autsky-jadek/p/3961610.html
Copyright © 2011-2022 走看看