51. N-Queens(js)

51. N-Queens

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 all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

Example:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
题意:n皇后问题,将n个皇后棋子放入nXn的棋盘格中,使得两两皇后不在同一行,不在同一列,不在同一对角线上,返回所有情况
代码如下:
/**
 * @param {number} n
 * @return {string[][]}
 */
//回溯
var solveNQueens = 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(curr,res,0)
    return res;
};
var backtrack = function(curr,res,row){
    if(curr.length===row){
        var c=[];
        for(var i=0;i<curr.length;i++){
            c.push(curr[i].join(''));
        }
        res.push(c);
        return ;
    }
   
        //遍历每一行所有元素
        for(var col=0;col<curr.length;col++){
            //判断该位置是否有效
            if(isValid(row,col,curr)){
                curr[row][col]="Q"
                backtrack(curr,res,row+1);
                curr[row][col]="."
            }
        }
    
};
var isValid=function(row,col,curr){
    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<curr.length ; i--,j++){
        if(curr[i][j]==="Q") return false;
    }
    return true;
    
};

 

posted @ 2019-02-26 19:39  mingL  阅读(127)  评论(0编辑  收藏  举报