zoukankan      html  css  js  c++  java
  • 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<>();
    }
  • 相关阅读:
    centos golang 环境配置
    运行安全审计 npm audit
    Oracle ——UTL_SMTP包发送Email
    UML学习入门就这一篇文章
    UML ——类图和对象图
    SQL SERVER 行列转换(转自别人)
    Oracle行列转换小结
    同步调用/异步调用(摘自百度)
    C#中Invoke的用法(Winform编程)
    udpclient之异步编程
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/11104781.html
Copyright © 2011-2022 走看看