链接:http://codeforces.com/contest/445/problem/A
题目:
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.
You task is to find any suitable placement of chessmen on the given chessboard.
The first line contains two space-separated integers n andm(1 ≤ n, m ≤ 100).
Each of the next n lines contains a string ofm characters: thej-th character of thei-th string is either "." or "-". A "." means that the corresponding cell (in thei-th row and thej-th column) is good, while a "-" means it is bad.
Output must contain n lines, each line must contain a string ofm characters. Thej-th character of thei-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell.
If multiple answers exist, print any of them. It is guaranteed that at least one answer exists.
1 1 .
B
2 2 .. ..
BW WB
3 3 .-. --- --.
B-B --- --B
解题思路:
一开始,我的思路是这样的,先读取整个棋盘,如果遇到‘-’跳过,遇到‘.’,就判断一下周围有没有‘B’,有‘B’的话,这个位置就放‘W’,没有‘B’的话,就放‘B’。后来才发现这样的思路是有问题的,因为之前的决策可能会对后面的决策造成影响,在后面可能会发生冲突的情况,就是在一个位置的四周既有‘B’又有‘W’,这样的话,就需要回溯去解决了,比较麻烦。比较好的思路是这样的:先假设棋盘所有的格子都是好的,在上面按条件放置‘B’和‘W’,最后将棋盘中坏的部分放上‘-’就可以了。
代码:
#include <cstdio>
#include <cstring>
const int MAXN = 110;
char map[MAXN][MAXN];
int d[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
int main()
{
int n, m, t = 0;
char c;
scanf("%d%d", &n, &m);
getchar();
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
int flag = 0;
for(int k = 0; k < 4; k++)
{
int x = i + d[k][0];
int y = j + d[k][1];
if(x >= 0 && x < n && y >= 0 && y < m)
{
if('B' == map[x][y])
{
flag = 1;
}
}
}
map[i][j] = flag ? 'W' : 'B';
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
scanf("%c", &c);
if('-' == c)
{
map[i][j] = c;
}
}
getchar();
}
for(int i = 0; i < n; i++)
{
puts(map[i]);
}
return 0;
}