51. N 皇后
题目
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
N后问题是: n 皇后在 n x n的棋盘上,且两两不能攻击。
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.
解里Q代表皇后,.代表空位
思路
MD N后是经典DP问题,我能有啥子思路?🤣
1. 遍历n * n次
2. 判断board[row][col]是否可以落子
其实是个经典的 回溯 问题,还是高斯搞出来的=- =
遍历次数也不是n^2,而是n!
查阅了资料找到个回溯的框架
|
|
接着就套公式咯~
代码
ts
|
|
go
|
|
赏析
无
最快的我自己测了速度也差不多 故不解释了