难度困难366收藏分享切换为英文接收动态反馈
n 皇后问题 研究的是如何将 n
个皇后放置在 n × n
的棋盘上,并且使皇后彼此之间不能相互攻击。
给你一个整数 n
,返回 n 皇后问题 不同的解决方案的数量。
示例 1:
输入:n = 4 输出:2 解释:如上图所示,4 皇后问题存在两个不同的解法。
示例 2:
输入:n = 1 输出:1
提示:
1 <= n <= 9
class Solution { //结果 static int cnt = 0; public int totalNQueens(int n) { int[] arr = new int[n]; //初始化 for (int i = 0; i < n; i++) { arr[i] = -1; } //从0行开始 count(arr, 0, n); return cnt; } public void count(int[] arr, int curn, int n) { //如果到达最后一行,说明成功 if (curn == n) { //回溯上一行 arr[curn - 1] = -1; cnt++; return; } //遍历每一列 for (int j = 0; j < n; j++) { //判断此列是否可以摆放棋子 if (isValid(arr, curn, j)) { arr[curn] = j; //计算下一行 count(arr, curn + 1, n); } } //不能拜访,回溯,将上一行还原 if (curn >= 1) arr[curn - 1] = -1; } public boolean isValid(int[] arr, int curn, int j) { for (int i = 0; i < curn; i++) { int k = arr[i]; if (j == k || Math.abs(i-curn) == Math.abs(k-j)) { return false; } } return true; } }