• 51. N-Queens (JAVA)


    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.
    
     

    注意:任意斜线也不能有两个Q

    class Solution {
        public List<List<String>> solveNQueens(int n) {
            List<String> ans = new ArrayList<String>();
            //initialize ans
            for(int i = 0; i < n; i++){
                StringBuilder s = new StringBuilder();
                for(int j = 0; j < n; j++){
                    s.append(".");
                }
                ans.add(s.toString());
            }
    
            dfs(n,0,ans);
            return ret;
        }
        
        public void dfs(int n, int depth, List<String> ans){
            
            if(depth == n) {
                List<String> new_ans = new ArrayList<String>(ans);
                ret.add(new_ans);
                return;
            }
            StringBuilder strBuilder = new StringBuilder(ans.get(depth));
            for(int i = 0; i < n; i++){
                if(check(n, ans, depth, i)) continue; //already have Q in this column
                
                strBuilder.setCharAt(i, 'Q');
                ans.set(depth, strBuilder.toString());
                dfs(n, depth+1, ans);
                strBuilder.setCharAt(i, '.'); //recover
                ans.set(depth, strBuilder.toString());
            }
        }
        
        public Boolean check(int n, List<String> ans, int i, int j){
            for(int k = 0; k < i; k++){ //iterate n line
                //i-k = j-x => x = j+k-i; i-k = x-j => x = i+j-k
                if( ans.get(k).charAt(j) == 'Q'
                   ||(j+k-i >= 0 && ans.get(k).charAt(j+k-i) == 'Q') 
                   || (i+j-k < n && ans.get(k).charAt(i+j-k) == 'Q')) 
                    return true;
            }
            
            return false;
        }
        
        private List<List<String>> ret = new ArrayList<>();
    }
  • 相关阅读:
    java打包成windows服务(转)
    java程序在windows系统作为服务程序运行(转)
    java String 转 Long 两种方法区别(转)
    css清除浮动clearfix:after的用法详解(转)
    管理界面的头2
    ROS 设置串口USB软连接
    ROS 用 roboware实现节点信息发送和接收
    javascript实现html中关键字查询
    winfrom 中 label 文字随着窗体大小变化
    lattice planner 规划详解
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/11104781.html
Copyright © 2020-2023  润新知