LeetCode进阶之路(N-Queens)

本文介绍了一种使用回溯法解决N皇后问题的方法,并提供了一个Java实现的例子。该算法能够找出所有可能的放置方案,使得N个皇后在N×N的棋盘上互不攻击。

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

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

题目:8皇后的问题,采用回溯法。有不明白的直接看回溯这篇文章(http://blog.youkuaiyun.com/yulingkai88/article/details/52108264)

关于N-Queens II,只是求数量,size就可以。

public class Solution {
    // static int p = 0;
    static int num;
    static int[] location;
    static List<List<String>> list = new ArrayList<List<String>>();
    public List<List<String>> solveNQueens(int n) {
        num = n;
        location = new int[n+1];
        findQueen(1);
        return list;
    }
    
    public void findQueen(int t) {//t表示第几行  
        if(t > num) {  
            // p++;//如果大于8,则找到一个解,输出  
            List<String> l = new ArrayList<String>();
            for(int i = 1;i < num+1;i++) {
                StringBuffer st = new StringBuffer();
                for(int j = 1;j <= num;j++) {
                    if(j == location[i]){
                        st.append("Q");
                    } else {
                        st.append(".");
                    }
                }
                l.add(st.toString());
            }
            list.add(l);
        } else {  
            for(int i = 1; i <= num;i++) {//下一个节点有n个选择  
                location[t] = i;//a[t]表示第几列  
                if(isValid(t)) {//符合皇后规则,继续寻找下一个节点。不符合,则寻找下一列.  
                    findQueen(t+1);  
                }  
            }  
        }  
    }  
    public boolean isValid(int t){//判断是否合法,即两个皇后既不能在同一行同一列同一斜线。  
        for(int i = 1;i < t;i++) {  
            if(Math.abs(t-i) == Math.abs(location[t]-location[i]) || location[i] == location[t]){  
                return false;  
            }  
        }  
        return true;  
    }  

种一棵树最好的时间是十年前,其次是现在!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值