AcWing P173 矩阵距离 题解

Analysis

就是一个裸的广搜,每次从是1的点开始找就好啦~~~

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<queue>
 6 #define maxn 1010
 7 using namespace std;
 8 inline int read() 
 9 {
10     int x=0;
11     bool f=1;
12     char c=getchar();
13     for(; !isdigit(c); c=getchar()) if(c=='-') f=0;
14     for(; isdigit(c); c=getchar()) x=(x<<3)+(x<<1)+c-'0';
15     if(f) return x;
16     return 0-x;
17 }
18 inline void write(int x)
19 {
20     if(x<0){putchar('-');x=-x;}
21     if(x>9)write(x/10);
22     putchar(x%10+'0');
23 }
24 queue<pair<int,pair<int,int> > > q;
25 int n,m;
26 int map[maxn][maxn];
27 int ans[maxn][maxn];
28 bool book[maxn][maxn];
29 int dx[10]={0,1,-1,0,0},dy[10]={0,0,0,1,-1};
30 int main()
31 {
32     n=read();m=read();
33     for(int i=1;i<=n;i++)
34     {
35         char ch;
36         for(int j=1;j<=m;j++)
37         {
38             cin>>ch;
39             map[i][j]=ch-'0';
40             if(map[i][j]==1)
41             {
42                 ans[i][j]=0;
43                 q.push(make_pair(0,make_pair(i,j)));
44             }
45         }
46     }
47     while(!q.empty())
48     {
49         int ex=q.front().second.first,ey=q.front().second.second,c=q.front().first;
50         q.pop();
51         for(int i=1;i<=4;i++)
52         {
53             int xx=ex+dx[i],yy=ey+dy[i];
54             if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&map[xx][yy]!=1&&book[xx][yy]==0)
55             {
56                 book[xx][yy]=1;
57                 ans[xx][yy]=c+1;
58                 q.push(make_pair(c+1,make_pair(xx,yy)));
59             }
60         }
61     }
62     for(int i=1;i<=n;i++)
63     {
64         for(int j=1;j<=m;j++)
65         {
66             write(ans[i][j]);
67             printf(" ");
68         }
69         printf("
");
70     }
71     return 0;
72 }
请各位大佬斧正(反正我不认识斧正是什么意思)
原文地址:https://www.cnblogs.com/handsome-zyc/p/11269789.html