• 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;
    };
  • 相关阅读:
    aspx页面,中文乱码解决方案
    使用JSP体验微信公众平台开发模式
    使用微信公众平台“编辑模式”的过程记录
    JAVA刷新网站IP访问量的技术探讨
    301. Remove Invalid Parentheses
    Dungeon Game
    刷题关键点总结-动态规划
    刷题关键点总结-单调栈、单调队列
    coin change
    常用vim命令
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10439603.html
Copyright © 2020-2023  润新知