Painter's Problem
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 6306 | Accepted: 3006 |
Description
There is a square wall which is made of n*n small square bricks. Some bricks are white while some bricks are yellow. Bob is a painter and he wants to paint all the bricks yellow. But there is something wrong with Bob's brush. Once he uses this brush to paint brick (i, j), the bricks at (i, j), (i-1, j), (i+1, j), (i, j-1) and (i, j+1) all change their color. Your task is to find the minimum number of bricks Bob should paint in order to make all the bricks yellow.
Input
The first line contains a single integer t (1 <= t <= 20) that indicates the number of test cases. Then follow the t cases. Each test case begins with a line contains an integer n (1 <= n <= 15), representing the size of wall. The next n lines represent the original wall. Each line contains n characters. The j-th character of the i-th line figures out the color of brick at position (i, j). We use a 'w' to express a white brick while a 'y' to express a yellow brick.
Output
For each case, output a line contains the minimum number of bricks Bob should paint. If Bob can't paint all the bricks yellow, print 'inf'.
Sample Input
2 3 yyy yyy yyy 5 wwwww wwwww wwwww wwwww wwwww
Sample Output
0 15
判断最后一行涂色是否满足要求正方形的最后一行。
AC代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 20;
const int INF = 0x3f3f3f3f;
int color[MAXN][MAXN];
int paint[MAXN][MAXN];
int n;
int judge() {
for (int i = 1; i < n; i++) {
for (int j = 1; j <= n; j++) {
paint[i + 1][j] = (color[i][j] + paint[i][j] + paint[i - 1][j] + paint[i][j - 1] + paint[i][j + 1]) % 2;
//根据上一格的颜色判断本格是否涂色
}
}
for (int i = 1; i <= n; i++) {
if ((paint[n][i] + paint[n][i - 1] + paint[n][i + 1] + paint[n - 1][i]) % 2 != color[n][i]) { //判断最后一行是否满足
return INF;
}
}
int ret = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (paint[i][j] == 1) {
ret++;
}
}
}
return ret;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
scanf("%d", &n);
memset(paint, 0, sizeof(paint));
for (int i = 1; i <= n; i++) {
char s[MAXN];
scanf("%s", s);
for (int j = 0; s[j]; j++) {
if (s[j] == 'w') {
color[i][j + 1] = 1;
} else {
color[i][j + 1] = 0;
}
}
}
int res = INF;
for (int i = 0; i < (1 << n); i++) {
for (int k = 0; k < n; k++) {
if (i & (1 << k)) {
paint[1][k + 1] = 1; //枚举第一行
} else {
paint[1][k + 1] = 0;
}
}
res = min(res, judge());
}
if (res == INF) {
printf("inf\n");
} else {
printf("%d\n", res);
}
}
return 0;
}