Backtracking· 25 min
N-Queens
Try, recurse, undo — DFS over partial solutions with pruning
Setup
Board size
Step 1 / 46
Current step
1 / 46Try a queen at row 0, column 0 — no queen attacks this square, it's safe.
Step log
?
Trying
Conflict
Placed
Solution
n_queens.java
1import java.util.Arrays;2 3public class Main {4 private final int size;5 private final int[] queens;6 7 public Main(int size) {8 this.size = size;9 this.queens = new int[size];10 Arrays.fill(queens, -1);11 }12 13 private boolean isSafe(int row, int col) {14 for (int previousRow = 0; previousRow < row; previousRow++) {15 int previousCol = queens[previousRow];16 if (previousCol == col || Math.abs(previousCol - col) == row - previousRow) return false;17 }18 return true;19 }20 21 public boolean solve(int row) {22 if (row == size) return true;23 for (int col = 0; col < size; col++) {24 if (isSafe(row, col)) {25 queens[row] = col;26 if (solve(row + 1)) return true;27 queens[row] = -1;28 }29 }30 return false;31 }32 33}● Java
Time
O(N!)
Space
O(N)
Board
5×5
Solutions found
0
