【洛谷习题】填涂颜色

题目链接:https://www.luogu.org/problemnew/show/P1162


好久没写博客了,这次一写竟是道搜索模板题。可见我水平下降很快。。。

这道题虽然简单,但细节颇多,需要注意的东西不少。虽然是用搜索找连通块,但起点怎么找呢?其实找内部的点不如找外部的点,反正只是要把几个连通块区分开。本以为这样就可以对,实际实现时却忽略了两点,可能没有外部的点,即1占满了边界;可能不止3个连通块,外部点可能不连通。

 1 #include<cstdio>
 2 #include<queue>
 3 using namespace std;
 4 const int maxn=35;
 5 const int mov[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
 6 int n,mt[maxn][maxn];
 7 struct point {
 8     int x,y;
 9     point(int x,int y):x(x),y(y) {}
10 };
11 queue<point> q;
12 void bfs(int sx,int sy) {
13     q.push(point(sx,sy));
14     while(!q.empty()) {
15         int nx=q.front().x,ny=q.front().y;q.pop();
16         mt[nx][ny]=2;
17         for(int i=0;i<4;++i) {
18             int a=nx+mov[i][0],b=ny+mov[i][1];
19             if(mt[a][b]||a<1||a>n||b<1||b>n) continue;
20             q.push(point(a,b));
21         }
22     }
23 }
24 int main() {
25     scanf("%d",&n);
26     for(int i=1;i<=n;++i)
27         for(int j=1;j<=n;++j) scanf("%d",&mt[i][j]);
28     for(int i=1;i<=n;++i) {
29         if(!mt[1][i]) bfs(1,i);
30         if(!mt[i][1]) bfs(i,1);
31         if(!mt[n][i]) bfs(n,i);
32         if(!mt[i][n]) bfs(i,n);
33     }
34     for(int i=1;i<=n;++i) {
35         if(i!=1) putchar('\n');
36         for(int j=1;j<=n;++j) {
37             if(j!=1) putchar(' ');
38             if(!mt[i][j]) printf("2");
39             else if(mt[i][j]==1) printf("1");
40             else printf("0");
41         }
42     }
43     return 0;
44 }
AC代码

猜你喜欢

转载自www.cnblogs.com/Mr94Kevin/p/9691914.html