首页 > 专题系列 > Java解POJ > POJ 1681 Painter’s Problem [解题报告] Java
2013
11-10

POJ 1681 Painter’s Problem [解题报告] Java

Painter’s Problem

问题描述 :

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.

输入:

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.

输出:

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’.

样例输入:

2
3
yyy
yyy
yyy
5
wwwww
wwwww
wwwww
wwwww
wwwww

样例输出:

0
15

解题代码:

//* @author:
import java.util.*;

public class Main {

 static Scanner in = new Scanner(System.in);
 static char[][] board;//用于保存初始状态
 static boolean[][] map;//墙壁的状态
 static int cnt;//涂块的次数
	
 static void click(int x, int y) {//涂(x,y)处的格子
	++cnt;
	map[x][y] = !map[x][y];
	if(x-1>=0) map[x-1][y] = !map[x-1][y];//上面的格子
	if(y-1>=0) map[x][y-1] = !map[x][y-1];//左边的格子
	if(x+1< map.length) map[x+1][y] = !map[x+1][y];//下面的格子
	if(y+1< map[x].length) map[x][y+1] = !map[x][y+1];//右边的格子
  }
	

 static int check(int s) {
   cnt = 0;
  for(int i=0; i!=map.length; ++i)//初始状态
	for(int j=0; j!=map[i].length; ++j)
		map[i][j] = board[i][j]=='w';
  for(int i=0; i!=map[0].length; ++i)//确定第一行的具体情况
           if((s&(1<< i))!=0)
		click(0, i);
				
  for(int i=1; i!=map.length; ++i)//涂第二行至最后一行
	   for(int j=0;j!=map[i].length; ++j)
		if(map[i-1][j]) click(i, j);
				
  for(int j=0; j!=map[map.length-1].length; ++j)//检查最后一行是否全是黄色
	if(map[map.length-1][j]) return Integer.MAX_VALUE;
		return cnt;
  }
	
	
 public static void main(String[] args) {
   int t = in.nextInt();//测试次数
   while(t-->0) {
	int n = in.nextInt();//格子的规模
	board = new char[n][];
	for(int i=0; i!=n; ++i) {
		board[i] = in.next().toCharArray();
	}
	map = new boolean[n][n];
	int ans = Integer.MAX_VALUE;
	for(int i=0; i!=(1 << n); ++i) {//第一行有2^n种变化,对每一种变化尝试
		ans = Math.min(ans, check(i));
	}
	if(ans< Integer.MAX_VALUE) System.out.println(ans);
	else System.out.println("inf");
   }
 }

}