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:1234567891011[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."]]
解法1: DFS, O(N^N )
每一行有N个位置可以尝试,一共有N个行,不同的摆放方法是N^N
要注意的是在存储一个特定的摆放时,一个list就能解决问题。每一个元素对应的是每一行的列的位置。
比较直接的DFS的解法
|
|