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.
描述
n 皇后问题,任意两个皇后都不能处于同一行、同一列或同一斜线上
分析
- 核心思想: 由于棋盘上每一行都只能放一个数,所以无需记录行的信息,这就便于将行折叠起来。这样整个棋盘便可以看成是一个二进制数,每个二进制位都是一列
- 注意: 回溯时,需要把棋盘的状态重置
代码
1 | import java.util.ArrayList; |