
Sponsored
Sponsored
This approach involves using backtracking to place queens row by row, exploring valid positions recursively. Each queen placement is validated based on column and diagonal restrictions. If a valid placement is found, the algorithm progresses to the next row, otherwise it backtracks and attempts alternative placements.
Time Complexity: O(N!), because we are trying N possible positions for each row for N queens.
Space Complexity: O(N^2), due to the storage of the board states and recursion stack.
1using System;
2using System.Collections.Generic;
3
4public class NQueens {
5 private List<IList<string>> result = new List<IList<string>>();
6
7 public IList<IList<string>> SolveNQueens(int n) {
8 char[][] board = new char[n][];
9 for (int i = 0; i < n; i++) {
10 board[i] = new char[n];
11 Array.Fill(board[i], '.');
12 }
13 bool[] cols = new bool[n];
14 bool[] d1 = new bool[2 * n];
15 bool[] d2 = new bool[2 * n];
16 Backtrack(board, 0, n, cols, d1, d2);
17 return result;
18 }
19
20 private void Backtrack(char[][] board, int row, int n, bool[] cols, bool[] d1, bool[] d2) {
21 if (row == n) {
22 List<string> solution = new List<string>();
23 foreach (var rowArray in board) {
24 solution.Add(new string(rowArray));
25 }
26 result.Add(solution);
27 return;
28 }
29
30 for (int col = 0; col < n; col++) {
31 int id1 = col - row + n;
32 int id2 = col + row;
33 if (!cols[col] && !d1[id1] && !d2[id2]) {
34 board[row][col] = 'Q';
35 cols[col] = d1[id1] = d2[id2] = true;
36 Backtrack(board, row + 1, n, cols, d1, d2);
37 board[row][col] = '.';
38 cols[col] = d1[id1] = d2[id2] = false;
39 }
40 }
41 }
42
43 static void Main() {
44 NQueens nq = new NQueens();
45 var solutions = nq.SolveNQueens(4);
46 foreach (var board in solutions) {
47 foreach (string row in board) {
48 Console.WriteLine(row);
49 }
50 Console.WriteLine();
51 }
52 }
53}In this C# solution, the board is maintained as a multidimensional character array. The backtracking proceeds by recursively trying queen positions and updating auxiliary column and diagonal boolean arrays to track conflicts. Valid boards are collected into the result list.
This approach optimizes the placement verification using bit manipulation, reducing the auxiliary space by managing columns and diagonals in integer bitmasks. This permits efficient bitwise operations for placing queens and checking potential attacks.
Time Complexity: O(N!), each row considers N placements, simplified by binary check.
Space Complexity: O(N), due to condensed state tracking via differential lists.
1import java.util.*;
2
3
This solution in Java embodies bit manipulation to track column and diagonal availability via bitmasks, ensuring low overhead while solving N-Queens recursively. Solutions are compiled as lists of strings to represent the board state efficiently.