杭电Acm-1045解题心得
这个题目比较好理解。在一个n*n的格子中,放尽可能多的碉堡。这个题目开始想的时候,如果就思考深度搜索或者宽度搜索,会得到错误的答案,因为,当两个碉堡之间有墙的时候,它们是可以在同一行,同一列出现的。也就是说,在遍历的过程中,一行一列是否可以放碉堡的状态是可变的。代码如下:
import java.util.Scanner;
public class P1045 {
private static int n, max;
private static byte[][] city;
private static byte[][] used;
private static byte[] hori, vert;
private static void trans(int num) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (0 == used[i][j] && 0 == hori[i] && 0 == vert[j]) {
if (1 == used[i][j]) continue;
used[i][j] = 1;
hori[i] = 1;
vert[j] = 1;
trans(num + 1);
used[i][j] = 0;
hori[i] = 0;
vert[j] = 0;
} else if (1 == city[i][j]) {
hori[i] = 0;
vert[j] = 0;
}
}
}
if (num > max) max = num;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
n = Integer.parseInt(in.nextLine());
if (0 == n) return;
city = new byte[n][n];
used = new byte[n][n];
hori = new byte[n];
vert = new byte[n];
max = 0;
for (int i = 0; i < n; ++i) {
String line = in.nextLine();
for (int j = 0; j < n; ++j) {
char c = line.charAt(j);
if ('X' == c) {
used[i][j] = 1;
city[i][j] = 1;
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (1 == used[i][j]) continue;
used[i][j] = 1;
hori[i] = 1;
vert[j] = 1;
trans(1);
used[i][j] = 0;
hori[i] = 0;
vert[j] = 0;
}
}
System.out.println(max);
}
}
}