好久没有做ACM的题目了,今天用Java来回顾一下,花了1个多小时做了ZJU的1002 Fire Net
用了类似八皇后问题的回溯。
现在已经通过。
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=2
2011-02-26 12:40:51 | Accepted | 1002 | Java |
另求高手指教
package acm.be.persist;
import java.util.Scanner;
/*
* FireNet 1002
* 2011/2/26
* Jiang
*/
public class Main {
public int result = 0, n;
public char[] tem[];
public void put(int x, int y, int count) {
if (x == n-1 && y == n-1) {
if(count > result){
result = count;
}
return;
}
if (y == n-1) {
y = -1;
x = x + 1;
}
if(tem[x][y+1] == '.' && judge(x, y+1)){
tem[x][y+1] = ' ';
put(x, y+1, count + 1);
tem[x][y+1] = '.';
}
put(x, y+1, count);
}
public boolean judge(int x, int y) {
for (int i = x - 1; i >= 0; i--) {
if (tem[i][y] == 'X') {
break;
}
if (tem[i][y] == ' ')
return false;
}
for (int i = y - 1; i >= 0; i--) {
if (tem[x][i] == 'X')
break;
if (tem[x][i] == ' ')
return false;
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Main fireNet = new Main();
fireNet.n = Integer.parseInt(sc.next());
while(fireNet.n != 0){
fireNet.tem = new char[fireNet.n][fireNet.n];
for (int i = 0; i < fireNet.n; i++) {
fireNet.tem[i] = sc.next().toCharArray();
}
for (int i = 0; i < fireNet.n; i++) {
for (int j = 0; j < fireNet.n; j++) {
if (fireNet.tem[i][j] == '.') {
fireNet.tem[i][j] = ' ';
fireNet.put(i, j, 1);
fireNet.tem[i][j] = '.';
}
}
}
System.out.println(fireNet.result);
fireNet.result = 0;
fireNet.n = Integer.parseInt(sc.next());
}
}
}