LeetCode - N-Queens I && II

本文深入探讨了N皇后问题及其进阶版本,详细阐述了解决N皇后问题的方法,并通过代码实例展示了如何求解不同规模的N皇后问题,以及如何计算总解数。同时,解释了代码实现中的关键逻辑,如如何使用递归和回溯技巧,以及如何检查皇后之间的冲突。最后,介绍了如何将解决方案应用到实际问题中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

N-Queens I

https://leetcode.com/problems/n-queens/

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.."]
]
这道题跟solve sudoku差不多,都是每个index挨个检查是否valid,如果valid就进入下一轮递归,否则就继续寻找。

注意这里,用一个LinkedList<Integer>来存已经生成的position,list中第i个元素j表示第i行的queen在第j列。这样简化了很多代码,不然直接操作string[]简直是灾难啊。

还有就是在检查对角线时,检查的是 Math.abs(row1-row2)==Math.abs(col1-col2),如果检查Math.abs(row1-col) == Math.abs(row2-col2)的话,只能检查一个方向的对象线,即从左上到右下的,不能检查从右上到左下的对角线。


从左上到右下的对角线上row-col值是相同的

从右上到左下的对角线row+col的值相同

两种都满足 Math.abs(row1-row2)==Math.abs(col1-col2)

public class Solution {
    public List<String[]> solveNQueens(int n) {
        List<String[]> rst = new LinkedList<String[]>();
        List<Integer> position = new LinkedList<Integer>();
        
        helper(rst, position, n);
        return rst;
    }
    
    public void helper(List<String[]> rst, List<Integer> position, int n){
        if(position.size()==n){
            genBoard(position, rst);
            return;
        }
        for(int i=0; i<n; i++){
            if(isValid(position, i)){
                position.add(i);
                helper(rst, position, n);
                position.remove(position.size()-1);
            }
        }
    }
    
    public boolean isValid(List<Integer> position, int col){
        int row = position.size();
        for(int i=0; i<position.size(); i++){
            if(col == position.get(i)) return false;
            if(Math.abs(row-i)==Math.abs(col-position.get(i))) return false;
        }
        return true;
    }
    
    public void genBoard(List<Integer> position, List<String[]> rst){
        String[] board = new String[position.size()];
        for(int i=0; i<position.size(); i++){
            int queen = position.get(i);
            StringBuilder sb = new StringBuilder();
            for(int j=0; j<position.size(); j++){
                if(j!=queen) sb.append('.');
                else sb.append('Q');
            }
            board[i] = sb.toString();
        }
        rst.add(board);
    }
}

N-Queen II

https://leetcode.com/problems/n-queens-ii/

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

这道题直接用上一道题的函数就可以了,只是当遇到一个solution的时候,不需要生成board,只需要count++就可以了。另外,由于JAVA都是值传递,所以如果

传给helper函数的是int count的话,那么helper中修改的count值不会生效,所以这里传一个int[] count数组,然后修改count[0],另一个方法是在类中设置一个全局变量。

public class Solution {
    public int totalNQueens(int n) {
        List<String[]> rst = new LinkedList<String[]>();
        List<Integer> position = new LinkedList<Integer>();
        int[] count = new int[1];
        
        helper(rst, position, n, count);
        return count[0];
    }
    
    public void helper(List<String[]> rst, List<Integer> position, int n, int[] count){
        if(position.size()==n){
            count[0]++;
            return;
        }
        for(int i=0; i<n; i++){
            if(isValid(position, i)){
                position.add(i);
                helper(rst, position, n, count);
                position.remove(position.size()-1);
            }
        }
    }
    
    public boolean isValid(List<Integer> position, int col){
        int row = position.size();
        for(int i=0; i<position.size(); i++){
            if(col == position.get(i)) return false;
            if(Math.abs(row-i)==Math.abs(col-position.get(i))) return false;
        }
        return true;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值