P1162 填涂颜色(bfs)

题目描述
由数字0组成的方阵中,有一任意形状闭合圈,闭合圈由数字1构成,围圈时只走上下左右4个方向。现要求把闭合圈内的所有空间都填写成2.例如:6×6的方阵(n=6),涂色前和涂色后的方阵如下:
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1

0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1

#include<iostream>
#include<queue>
using namespace std;
int n, map[32][32] = { 0 }, a[32][32];
queue <int >q;
void bfs(int i,int j) {
 map[i][j] = 1;
 q.push(i);
 q.push(j);
 while (!q.empty())
 {
  int w = q.front();
  q.pop();
  int e = q.front();
  q.pop();
  if (!a[w + 1][e] && !map[w + 1][e] && w != n + 1) { map[w + 1][e] = 1;q.push(w + 1);q.push(e); }
  if (!a[w][e + 1] && !map[w][e + 1] && e != n+1) { map[w][e + 1] = 1;q.push(w);q.push(e + 1); }
  if (!a[w][e - 1] && !map[w][e - 1] && e != 0) { map[w][e - 1] = 1;q.push(w);q.push(e - 1); }
  if (!a[w - 1][e] && !map[w - 1][e] && w != 0) { map[w - 1][e] = 1;q.push(w - 1);q.push(e); }
 }
}
int main() {
 cin >> n;
 a[32][32] = { 0 };
 for (int i = 1;i <= n;i++) {
  for (int j = 1;j <= n;j++) {
   cin >> a[i][j];
   map[i][j] = a[i][j];
  }
 }
 bfs(0, 0);
 for (int k = 1;k <= n;k++) {
  for (int m = 1;m <= n;m++) {
   if (map[k][m] == 0)cout << "2" << " ";
   else { 
    if (m == n)cout << a[k][m];
                else cout << a[k][m] << " "; }
  }
  cout << endl;
 }
 return 0;
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值