52. N-Queens II(js)

52. N-Queens II

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
题意:给出n个皇后棋子求出有几种满足n皇后的情况
代码如下:
/**
 * @param {number} n
 * @return {number}
 */
var totalNQueens = function(n) {
    var res=[];
    var curr=[];
    for(var i=0;i<n;i++){
        curr[i]=new Array();
        for(var j=0;j<n;j++){
            curr[i][j]='.'
        }
    }
    backtrack(res,curr,0,n);
    return res.length;
};
var backtrack=function(res,curr,row,n){
    if(curr.length===row){
        var c=[];
        for(var i=0;i<n;i++){
            c.push(curr[i].join(''))
        }
        res.push(c)
    }
    for(var col=0;col<n;col++){
        if(isValid(row,col,curr,n)){
            curr[row][col]="Q";
            backtrack(res,curr,row+1,n);
            curr[row][col]=".";
        }
    }
};
var isValid=function(row,col,curr,n){
    for(var i=0;i<row;i++){
        if(curr[i][col]==="Q") return false;
    }
    for(var i=row-1,j=col-1;i>=0 && j>=0;i--,j--){
        if(curr[i][j]==='Q') return false;
    }
    for(var i=row-1,j=col+1;i>=0 && j<n;i--,j++){
        if(curr[i][j]==="Q") return false;
    }
    return true;
};

猜你喜欢

转载自www.cnblogs.com/xingguozhiming/p/10439603.html