c++之染色问题.bfs

洛谷题《P1162 填涂颜色》以BFS解决。

#include
using namespace std;
int a[40][40], n;
bool vis[40][40];
struct pos {
	int x, y;
	pos(int ax = 0, int ay = 0) {
		x = ax;
		y = ay;
	}
};
bool judge(int x, int y) {//是否压进队列
	if (a[x][y] == 1 || vis[x][y])return false;
	if (x < 0 || x > n + 1 || y < 0 || y > n + 1)return false;
	return true;
}
int main() {
	cin >> n;
	for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) {
			cin >> a[i][j];
			if (a[i][j] == 0)a[i][j] = 2;
		}
	queueq;
	pos now;
	q.push(pos(0, 0));//强制压(0,0)

	while (!q.empty()) {
		now = q.front();
		q.pop();
		vis[now.x][now.y] = 1;
		a[now.x][now.y] = 0;

		if (judge(now.x - 1, now.y))q.push(pos(now.x - 1,now.y));//别压a[][]
		if (judge(now.x + 1, now.y))q.push(pos(now.x + 1,now.y));
		if (judge(now.x, now.y - 1))q.push(pos(now.x,now.y - 1));
		if (judge(now.x, now.y + 1))q.push(pos(now.x,now.y + 1));
	}
	
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++)cout << a[i][j] << ' ';
		cout << endl;
	}
	return 0;
}

你可能感兴趣的:(知识资料库,c++,数据结构,开发语言)