[leetcode] 51 N皇后(路径打印+DFS+回溯)

n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

上图为 8 皇后问题的一种解法。

给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。

每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。

示例:

输入: 4
输出: [
 [".Q..",  // 解法 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // 解法 2
  "Q...",
  "...Q",
  ".Q.."]
]
解释: 4 皇后问题存在两个不同的解法。

class Pair{
    public int x;
    public int y;
    public Pair(int x,int y){
        this.x = x;
        this.y = y;
    }
}
class Solution {
//深搜过程
    public void dfs(List> listList,List list,int curRow,int n){
        if(curRow == n){
            List newP = new ArrayList<>();
            for(Pair p:list){
                newP.add(p);
            }
            listList.add(newP);
            return;
        }
        for(int i = 0;i list, int i, int curRow) {
        for(Pair pair:list){
            if(pair.y == i || i+curRow == pair.y+pair.x || curRow-i == pair.x-pair.y)
                return false;
        }
        return true;
    }
//打印图形
    public List> toStringQueue(List> solutions,int n){
        List> ret = new ArrayList<>();
        List tmp = new ArrayList<>();
        for(List solution:solutions){
            List solutionString = new ArrayList<>();
            for(int i = 0;i curRet = new ArrayList<>();
            for(StringBuilder sb:solutionString){
                curRet.add(sb.toString());
            }
            ret.add(curRet);
        }
        return ret;
    }
    public List> solveNQueens(int n) {
        List> lists = new ArrayList<>();
        List list = new ArrayList<>();
        dfs(lists,list,0,n);
        return toStringQueue(lists,n);
    }
}

测试

n = 4

[leetcode] 51 N皇后(路径打印+DFS+回溯)_第1张图片

你可能感兴趣的:(LeetCode)