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

题意解析:

这道题是说,给出一个整数n,有n个皇后,棋盘大小n * n,请问有几种排列可以让皇后之间不互相攻击。

解题思路:

这道题可以很快地想到两个思路,一个是全排列,一个是回溯法。

下面是回溯法代码,代码总体比较简单,只要注意几个注意点,一个是回溯的时候,要把queens[row]的值清0;还有一个是要注意什么情况下会导致皇后可以互相攻击。我用的是逐行深度遍历,也可以写逐列的,道理是一样的。

public class Solution {
    
    private List<List<String>> result;
    public List<List<String>> solveNQueens(int n) {
        result = new ArrayList<List<String>>();
        int[] queens = new int[n];//queens数组:queens[i] = j表示皇后在第i行第j列
        backTracking(queens, n, 0);
        return result;
    }
    public void backTracking(int[] queens, int n, int row){
        for(int col = 0; col < n; col++){
            if(check(queens, n, row, col)){
                queens[row] = col;
                if(row == n - 1){
                    resultAdd(queens, n);
                    queens[row] = 0;
                    return;
                }
                backTracking(queens, n, row + 1);
                queens[row] = 0;
            }
        }
    }
    public boolean check(int[] queens, int n, int row, int col){
        for(int i = 0; i < row; i++){
            //三种情况不成立:正斜线(q[i]-i=q[j]-j),反斜线(q[i]+i=q[j]+j),列相等,注意这里行是不可能相等的
            if(queens[i] == col || queens[i] + i == col + row || queens[i] - i == col - row){
                return false;
            }
        }
        return true;
    }
    public void resultAdd(int[] queens, int n){
        List<String> res = new ArrayList<String>();
        for(int i = 0; i < n; i++){
            String x = "";
            for(int j = 0; j < n; j++){
                if(j == queens[i]){
                    x += "Q";
                }else{
                    x += ".";
                }
            }
            res.add(x);
        }
        result.add(res);
    }
}


leetcode正在修复代码时间分布图。。只好过段时间再看了。希望还能想起来这件事。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值