• LeetCode 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.

    For example,
    There exist two distinct solutions to the 4-queens puzzle:

    [
     [".Q..",  // Solution 1
      "...Q",
      "Q...",
      "..Q."],
    
     ["..Q.",  // Solution 2
      "Q...",
      "...Q",
      ".Q.."]
    ]

    java解法如下所示:

    public class Solution {
        public void dfs(List<List<String>> res, List<String> list, Set<Integer> col, Set<Integer> diag1, Set<Integer> diag2, int row, int n){
            if(row==n){
                res.add(new ArrayList<String>(list));
                return;
            }
            //遍历该行的所有列
            for(int i=0;i<n;i++){
                if(col.contains(i)||diag1.contains(row+i)||diag2.contains(row-i))
                    continue;
                col.add(i);
                diag1.add(row+i);
                diag2.add(row-i);
                char[] rowChar = new char[n];
                Arrays.fill(rowChar, '.');
                rowChar[i] = 'Q';
                String rowString = new String(rowChar);
                list.add(rowString);
                //继续搜索下一行
                dfs(res, list, col, diag1, diag2, row+1, n);
                //搜索完成后释放所用资源
                list.remove(list.size()-1);
                col.remove(i);
                diag1.remove(row+i);
                diag2.remove(row-i);
            }
        }
        public List<List<String>> solveNQueens(int n) {
            List<List<String>> res = new ArrayList<List<String>>();
            if(n==0)
                return res;
            Set<Integer> col = new HashSet<Integer>(); //列集
            Set<Integer> diag1 = new HashSet<Integer>(); //正对角线集
            Set<Integer> diag2 = new HashSet<Integer>(); //副对角线集
            List<String> list = new ArrayList<String>(); //用于存放每一种情况
            dfs(res, list, col, diag1, diag2, 0, n);
            return res;
        }
    }
    
    
  • 相关阅读:
    记一次简单的SQL优化
    JAVA 根据数据库表内容生产树结构JSON数据
    Maven 整合FreeMarker使用
    JAVA FreeMarker工具类
    JAVA 分页工具类及其使用
    JAVA 日期格式工具类DateUtil.java
    JAVA 读写Excel
    简单Linux命令学习笔记
    WEB安全隐患
    metasploit 连接database相关问题
  • 原文地址:https://www.cnblogs.com/gaopeng527/p/4860162.html
Copyright © 2020-2023  润新知