洛谷CF445ADZY Loves Chessboard

版权声明:晓程原创 https://blog.csdn.net/qq_43469554/article/details/89089438

一个棋盘上有一些格子是坏的,另一些是正常的。对于每一个正常的格子,都要在上面放上棋子。 请找到一组解使没有两个相同颜色的棋子相邻(两个格子相邻为它们存在共同的边)

输入格式: 第一行为两个数n,m。(1<=n,m<=100) 下面n行,每个格子上的字符为’-‘或’.’,’-‘表示坏掉的格子,’.'表示正常的格子。

输出格式: 输出n行,每行m个字符。第i个字符串的第j个字符应为“W”,“B”或“ - ”。字符“W”是指在格子上放白色的棋子,“B”意味着放黑色的棋子,“ - ”表示坏掉的格子。 如果有多组答案,输出其中的一个。
原题链接:https://www.luogu.org/problemnew/show/CF445A

#include <iostream>
#include <cstdio>
using namespace std;
char s[105][105];
int n, m;
int dir[4][2] = { {1, 0}, {0, 1}, {0, -1}, {-1, 0} };
void dfs(int x, int y, char c)
{
	s[x][y] = c;
	for (int i = 0; i < 4; i++)
	{
		int tx = x + dir[i][0];
		int ty = y + dir[i][1];
		if (tx < 0 || tx >= n || ty < 0 || ty >= m)
		{
			continue;
		}
		if (s[tx][ty] == '.')
		{
			//当前4个方向是相邻的,不能同时为B或者W 
			if (c == 'B')
			{
				dfs(tx, ty, 'W');
			}
			else
			{
				dfs(tx, ty, 'B');
			}
		}
	}
}
int main()
{
	cin >> n >> m;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			cin >> s[i][j];
		}
	}
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (s[i][j] == '.')
			{//只要是‘.’就搜索四个方向是否还存在‘.’
				dfs(i, j, 'B');
			}
		}
	}
	
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{

			cout << s[i][j];
		}
		cout << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43469554/article/details/89089438
今日推荐