51. N-Queens

https://leetcode.com/problems/n-queens/

the idea is do dfs from the first row to the last row, put in col one by one, and validate the correctness.

so we only need to check top above(top-left, top, top-right ), if there are Queen, return false

top: loop row from 0 to current row -1

top-left : like (. row - k, col -k), k start from 1

top-right: (row - k, col + k) k start from 1

T: O(n^n), but a lot of pruning, so it's fast

S: O(n^2)

Last updated

Was this helpful?