LeetCode 102 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.."]
]

分析,这是典型的递归遍历,感觉也不是典型意义上的回溯,只是对每一行,列举所有可能的情况,然后进入下一步递归。

具体这道题,可以用一个一维数组来表示棋盘,下标表示行,内容表示列,这样就确定了每行皇后的位置。

对每一行,尝试把皇后放在每一个位置,如果放置合法,就进去下一层递归。

public class Solution {
    public List<String[]> solveNQueens(int n) {
        //典型递归题
        List<String[]> res = new ArrayList<String[]>();
        //一维数组表示棋盘,下标表示行,内容表示列
        int[] loc = new int[n];
        dfs(res, loc, 0, n);
        return res;
    }
    
    public void dfs(List<String[]> res, int[] loc, int cur, int n){
        if(cur == n)
            printBoard(res, loc, n);
        else
            //分别尝试在当前行各个列放王后
            for(int i=0; i<n; i++){
                loc[cur] = i;
                //如果当前行合法,可以尝试下一行
                if(isValid(loc, cur))
                    dfs(res, loc, cur+1, n);
            }
    }
    
    public boolean isValid(int[] loc, int cur){
        for(int i=0; i<cur; i++){
            //检查列,两对角线,行在这里已经保证只有一个
            if(loc[i]==loc[cur] || Math.abs(loc[i]-loc[cur])==(cur-i))
                return false;
        }
        return true;
    }
    //把一维棋盘翻译成结果
    public void printBoard(List<String[]> res, int[] loc, int n){
        String[] ans = new String[n];
        for(int i=0; i<n; i++){
            StringBuilder row = new StringBuilder();
            for(int j=0; j<n; j++){
                //此列放皇后
                if(j==loc[i])
                    row.append("Q");
                else
                    row.append(".");
            }
            ans[i] = row.toString();
        }
        res.add(ans);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值