# 51. N-Queens

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

{% embed url="<https://leetcode-cn.com/problems/n-queens/solution/gen-ju-di-46-ti-quan-pai-lie-de-hui-su-suan-fa-si->" %}

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)

```java
class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> res = new ArrayList<>();
        
        char[][] board = new char[n][n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(board[i], '.');
        }
        dfs(0, board, res);
        return res;
    }
    private void dfs(int row, char[][] board, List<List<String>> res) {
        int n = board.length;
        
        if (row == n) {
            addToResult(board, res);
            return;
        }
        
        // try this row, each col data
        for (int col = 0; col < n; col++) {
            if (isValid(board, row, col)) {
                board[row][col] = 'Q';
                dfs(row+1, board, res); // drill down to next row
                board[row][col] = '.';
            }
        }
    }
    private void addToResult(char[][] board, List<List<String>> res) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < board.length; i++) {
            list.add(String.valueOf(board[i]));
        }
        res.add(list);
    }
    private boolean isValid(char[][] board, int row, int col) {
        // check top (0~row, same col)
        for (int i = 0; i < row; i++) { // entire col
            if (board[i][col] == 'Q') {
                return false;
            }
        }
        // this don't need check, we just check above this (row, col)'s data
        //for (int j = 0; j < col; j++) { // entire row
        //    if (board[row][j] == 'Q') {
        //        return false;
        //    }
        //}
        
        int k = 1; // 左上角, top-left
        while (row - k >= 0 && col - k >= 0) {
            if (board[row - k][col - k] == 'Q') {
                return false;
            }
            k++;
        }
        k = 1; // 右上角, top-right
        while (row - k >= 0 && col + k < board.length) {
            if (board[row - k][col + k] == 'Q') {
                return false;
            }
            k++;
        }
        return true;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/dfs-and-bfs/dfs/tips/51.-n-queens.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
