P1162 填涂颜色

题目描述

由数字0组成的方阵中,有一任意形状闭合圈,闭合圈由数字11构成,围圈时只走上下左右4个方向。现要求把闭合圈内的所有空间都填写成2.例如:6×6的方阵(n=6n=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

输入格式:

每组测试数据第一行一个整数n(1≤n≤30)

接下来n行,由0和1组成的n×n的方阵。

方阵内只有一个闭合圈,圈内至少有一个0。

输出格式:

已经填好数字2的完整方阵。

输入样例#1

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

输出样例#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

说明

1≤n≤30

题目分析

我们可以对1围住区域的外面,进行广搜,非1就使其为2。

打印的时候,区分好情况就行。

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <queue>
using namespace std;
int m[100][100];
int dir[][2] = { {1,0},{0,1},{-1,0},{0,-1} };
int n;
struct node {
	int x, y;
	node(int a, int b) {
		x = a;
		y = b;
	}
};
bool check(int a, int b) {
	if (a > n || a < 0 || b > n || b < 0)
		return false;
	return true;
}
void bfs() {
	queue<node> q;
	for (int i = 0; i < n; i++) {
		if (m[i][0] == 0)
			q.push(node(i, 0));
		if (m[0][i] == 0)
			q.push(node(0, i));
		if (m[i][n-1] == 0)
			q.push(node(i, n-1));
		if (m[n-1][i] == 0)
			q.push(node(n-1, i));
	}
	while (!q.empty()) {
		node t = q.front();
		q.pop();
		m[t.x][t.y] = 2;
		for (int i = 0; i < 4; i++) {
			int xx = t.x + dir[i][0];
			int yy = t.y + dir[i][1];
			if(m[xx][yy] == 0 && check(xx, yy))
				q.push(node(xx, yy));
		}
	}
}
int main(){

	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			scanf("%d", &m[i][j]);
		}
	}
	bfs();
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (m[i][j] == 2)
				cout << 0 << " ";
			else if (m[i][j] == 0)
				cout << 2 << " ";
			else
				cout << 1 << " ";
		}
		cout << endl;
	}

	return 0;
}
原文地址:https://www.cnblogs.com/woxiaosade/p/10635784.html