[LeetCode] 51. N-Queens

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:
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

Thought process:
Search for every permutation of numbers from 1 to n. For every permutation, check if any two queens will attack each other. It's straightforward to check if two queens are on the same column. To check if two queens are on the same diagonal:
  1. Top-left to bottom-right: if one queen is at the top-left corner of a diagonal and the other is at the bottom-right, then row1 - col1 = row2 - col2.
  2. Top-right to bottom-left: if one queen is at the top-right corner of a diagonal and the other is at the bottom-left, then row1 + col1 = row2 + col2.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> boards = new ArrayList<>();
        List<Integer> columns = new ArrayList<>();
        solveNQueens(n, columns, boards);
        
        return boards;
    }
    
    private void solveNQueens(int n, List<Integer> columns, List<List<String>> boards) {
        if (columns.size() == n) {
            List<String> board = convertColumnsToBoard(columns);
            boards.add(board);
        }
        
        for (int i = 0; i < n; i++) {
            if (wontAttack(i, columns)) {
                columns.add(i);
                solveNQueens(n, columns, boards);
                columns.remove(columns.size() - 1);
            }
        }
    }
    
    private List<String> convertColumnsToBoard(List<Integer> columns) {
        List<String> board = new ArrayList<>();
        
        for (int i = 0; i < columns.size(); i++) {
            StringBuilder row = new StringBuilder();
            
            for (int j = 0; j < columns.size(); j++) {
                if (j == columns.get(i)) {
                    row.append('Q');
                } else {
                    row.append('.');
                }
            }
            
            board.add(row.toString());
        }
        
        return board;
    }
    
    private boolean wontAttack(int column, List<Integer> columns) {
        for (int i = 0; i < columns.size(); i++) {
            int row = columns.size();
            int existing = columns.get(i);
            
            if (column == existing) {
                return false;
            }
            if (row + column == i + existing) {
                return false;
            }
            if (row - column == i - existing) {
                return false;
            }
        }
        
        return true;
    }
}

Time complexity: O(n! * n^2).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula