LeetCode 10.4 N-Qeens

本文介绍了一种解决N皇后问题的方法,通过深度优先搜索(DFS)算法寻找所有可能的解决方案,使得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.."]
]

import java.util.Stack;

public class T1 {

T1(int _n) {

n = _n;

f = new int[n];

}

int n;

int[] f;

Stack<int[]> ans = new Stack<>();

public static void main(String[] args) {

T1 t = new T1(8);

t.DFS(0);

t.print();

}

void DFS(int k) {

if (k == n) {

if (chack(n)) {

int[] a = new int[n];

for (int i = 0; i < f.lengthi++) {

a[i] = f[i];

}

ans.push(a);

}

else {

for (int i = 0; i < ni++) {

f[k] = i;

if (chack(k))

DFS(k + 1);

}

}

}

boolean chack(int l) {

for (int i = 0; i < li++) {

for (int j = i + 1; j < lj++) {

if (Math.abs(f[j] - f[i]) == j - i || f[j] == f[i]) {

return false;

}

}

}

return true;

}

void print() {

int num = 1;

while (!ans.isEmpty()) {

System.out.println("============" + num + "=======");

int[] arr = ans.pop();

for (int i = 0; i < ni++) {

for (int j = 0; j < nj++) {

if (arr[i] != j)

System.out.print('.');

else

System.out.print('*');

}

System.out.println();

}

num++;

}

}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值