您的位置:首页 > 产品设计 > UI/UE

LeetCode刷题笔录N-Queens II

2014-08-21 04:09 411 查看
Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.



做法和N-Queens一样,也是用递归在每一行尝试放一个棋子,并判断是否合法。这里要记录的是方法总数,比N-Queens要简单一点。

public class Solution {
public int totalNQueens(int n) {
int[] result = new int[1];
result[0] = 0;
recursive(result, n, 0, new int
);
return result[0];
}

public void recursive(int[] result, int n, int row, int[] places){
if(row == n){
result[0] = result[0] + 1;
return;
}
for(int col = 0; col < n; col++){
if(checkValid(row, col, places)){
places[row] = col;
recursive(result, n, row + 1, places);
}
}
}

public boolean checkValid(int row, int col, int[] places){
for(int i = 0; i < row; i++){
if(col == places[i])
return false;
if((row - i) == Math.abs(col - places[i]))
return false;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: