枚举法 主要需要尽量减小枚举的次数,排除不必要的枚举。可通过事先排好顺序等方法。
POJ 1681
Painter's Problem
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.
![](https://i-blog.csdnimg.cn/blog_migrate/7d20b479261eb8fa1c1f3f948676182f.jpeg)
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
Source
#include <stdio.h>
#include <string.h>int row=0;
int min;
void enumerate(int press[][17], int plant[][17]);
int main() {
int num;
scanf("%d", &num);
while (num--) {
int plant[16][17] = { 0 };
int press[16][17] = { 0 };
scanf("%d", &row);
getchar();
char s[15];
int i, j;
for (i = 1; i<row + 1; i++) {
gets(s);
for (j = 1; j<row + 1; j++) {
if (s[j-1] == 'w') {
plant[i][j] = 1;
}
else {
plant[i][j] = 0;
}
}
}
enumerate(press, plant);
if (min == -1)
printf("inf\n");
else
printf("%d\n", min);
}
return 0;
}
void enumerate(int press[][17], int plant[][17]) {
int c;
min = -1;
int num = 1;
for (c = 1; c<row + 1; c++) {
press[1][c] = 0;
num *= 2;
}
while (num--) {
if (guess(press, plant)) {
int i, j, count = 0;
for (i = 1; i<row + 1; i++) {
for (j = 1; j<row + 1; j++) {
if (press[i][j] == 1) {
count++;
}
}
}
if (count<min&&min>0) {
min = count;
}
if (min == -1) {
min = count;
}
}
press[1][1]++;//二进制模拟进位 列举所有情况
c = 1;
while (press[1][c]>1) {
press[1][c] = 0;
c++;
press[1][c] ++;
}
}
}
int guess(int press[][17], int plant[][17]) {
int c, r;
for (r = 1; r<row; r++) {
for (c = 1; c<row + 1; c++) {//使得前row-1行满足条件
press[r + 1][c] = (plant[r][c] + press[r][c] + press[r - 1][c] + press[r][c - 1] + press[r][c + 1]) % 2;
}
}
for (c = 1; c<row + 1; c++) {//判断最后一行是否满足条件
if ((press[row][c - 1] + press[row][c] + press[row][c + 1] + press[row - 1][c]) % 2 != plant[row][c]) {
return 0;
}
}
return 1;
}