博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode——N-Queens
阅读量:6999 次
发布时间:2019-06-27

本文共 1385 字,大约阅读时间需要 4 分钟。

Description:

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皇后问题,有一个经典的回溯法。具体请参考: 在这个问题中需要用List来记录sum个解矩阵,并返回。 代码:
public class Solution {        public int[] x; //当前解    public int sum; //解的个数    public int n; //皇后个数    public List
> resList; public List
> solveNQueens(int n) { this.resList = new ArrayList
>(); for(int i=0; i
n) { List
pRes = new ArrayList
(); for(int i=1; i<=n; i++) { StringBuilder row = new StringBuilder(); for(int j=1; j<=n; j++) { if(this.x[i] == j) { row.append("Q"); } else { row.append("."); } } pRes.add(row.toString()); } resList.add(pRes); sum ++; } else { for(int i=1; i<=n; i++) { this.x[t] = i; if(place(t)) { backTrack(t + 1); //回溯 } } } } /** * 判断当前位置是否合法 */ public boolean place(int k) { for(int j=1; j

 

 

转载于:https://www.cnblogs.com/wxisme/p/4845233.html

你可能感兴趣的文章