技巧
回溯
思路
简单版8皇后问题
实现
import java.io.*; public class Main { private static boolean judge(boolean[] visit, int pos, int n) { while (pos >= 0) { if (visit[pos]) { return false; } pos -= n; } return true; } private static int process(int row, int n, int k, String[] chessBoard, boolean[] visit) { if (k == 0) { return 1; } if (row == n || k > n - row) { return 0; } int cnt = 0; for (int j = 0; j < n; j++) { if (chessBoard[row].charAt(j) != '.' && judge(visit, row * n + j, n)) { visit[row * n + j] = true; cnt += process(row + 1, n, k - 1, chessBoard, visit); visit[row * n + j] = false; } } return cnt + process(row + 1, n, k, chessBoard, visit); } public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); while (true) { String[] nk = br.readLine().split(" "); int n = Integer.parseInt(nk[0]); int k = Integer.parseInt(nk[1]); if (n == -1 && k == -1) { return; } String[] chessBoard = new String[n]; for (int i = 0; i < n; i++) { chessBoard[i] = br.readLine(); } System.out.println(process(0, n, k, chessBoard, new boolean[n * n])); } } }