• 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<>();
    }
  • 相关阅读:
    winform+cefSharp实现窗体加载浏览器
    C# 实现Mqqtnet 客户端,订阅发布信息
    winform+CefSharp 实现和js交互
    C# 读取INI文件
    H5+asp.net 微信开发 遇到过的坑
    C#读取Excel文件,准换为list
    vmware pro 15.5.5 官方下载地址
    IOS部分APP使用burpsuite抓不到包原因
    CVE-2020-0796 SMBv3本地提权
    网络摄像头rtsp协议登录认证
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/11104781.html
Copyright © 2020-2023  润新知