浙江大学1002题解-java
import java.util.Scanner; public class Main { private static int n; private static int max; private static Character[][] cs; public static void main(String[] args) { Scanner input = new Scanner(System.in); String[] strs; while(input.hasNext()) { n = input.nextInt(); max = 0; if(n == 0) { break; } cs = new Character[n][n]; strs = new String[n]; input.nextLine(); for(int i = 0; i < n; i++) { strs[i] = input.nextLine(); } for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cs[i][j] = strs[i].charAt(j); } } solve(0, 0); System.out.println(max); } input.close(); } public static void solve(int x, int total) { //total表示计数 到目前为止能摆放多少 if(x == n*n) { if(total > max) { max = total; return; } } else { int r = x/n; int c = x%n; if(cs[r][c] == '.' && CanPut(r, c) == 1) { cs[r][c] = 'o'; solve(x+1, total+1); cs[r][c] = '.'; //关键一步 } solve(x+1, total); } } public static int CanPut(int r, int c) { for(int i = r; i >= 0; i--) { if(cs[i][c] == 'o') return 0; if(cs[i][c] == 'X') break; } for(int i = c; i >= 0; i--) { if(cs[r][i] == 'o') return 0; if(cs[r][i] == 'X') break; } return 1; } }