🧠
Brute Force (Pure Recursion with Board Validation)
💡 This approach tries every possible placement of queens on the board and checks if the board is valid after each placement. It is slow but helps understand the problem deeply.
Intuition
Place queens row by row, and for each row try every column. After placing a queen, check if the board is still valid by scanning all previously placed queens.
Algorithm
- Start from the first row.
- Try placing a queen in each column of the current row.
- After placing, check if the board is valid (no two queens attack).
- If valid, recurse to the next row; if all rows are placed, record the solution.
💡 The main challenge is the validation step after each placement, which is costly and repeated many times.
def solveNQueens(n):
def is_valid(board, row, col):
for i in range(row):
for j in range(n):
if board[i][j] == 'Q':
if j == col or abs(row - i) == abs(col - j):
return False
return True
def backtrack(row, board, solutions):
if row == n:
solutions.append([''.join(r) for r in board])
return
for col in range(n):
board[row][col] = 'Q'
if is_valid(board, row, col):
backtrack(row + 1, board, solutions)
board[row][col] = '.'
board = [['.' for _ in range(n)] for _ in range(n)]
solutions = []
backtrack(0, board, solutions)
return solutions
# Example usage:
if __name__ == '__main__':
print(solveNQueens(4))
Line Notes
def is_valid(board, row, col):Defines a helper to check if placing a queen at (row, col) is safe
for i in range(row):Check all previously placed queens in rows above current row
if j == col or abs(row - i) == abs(col - j):Check same column or diagonal conflicts
if row == n:Base case: all rows have queens placed, record solution
import java.util.*;
public class NQueensBrute {
public List<List<String>> solveNQueens(int n) {
List<List<String>> solutions = new ArrayList<>();
char[][] board = new char[n][n];
for (int i = 0; i < n; i++) Arrays.fill(board[i], '.');
backtrack(0, board, solutions, n);
return solutions;
}
private void backtrack(int row, char[][] board, List<List<String>> solutions, int n) {
if (row == n) {
List<String> solution = new ArrayList<>();
for (char[] r : board) solution.add(new String(r));
solutions.add(solution);
return;
}
for (int col = 0; col < n; col++) {
board[row][col] = 'Q';
if (isValid(board, row, col, n)) {
backtrack(row + 1, board, solutions, n);
}
board[row][col] = '.';
}
}
private boolean isValid(char[][] board, int row, int col, int n) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'Q') {
if (j == col || Math.abs(row - i) == Math.abs(col - j)) return false;
}
}
}
return true;
}
public static void main(String[] args) {
NQueensBrute solver = new NQueensBrute();
System.out.println(solver.solveNQueens(4));
}
}
Line Notes
public List<List<String>> solveNQueens(int n)Entry point to solve the problem and store solutions
for (int col = 0; col < n; col++)Try placing queen in each column of current row
if (isValid(board, row, col, n))Check if current placement is safe before recursing
if (row == n)All queens placed, add current board to solutions
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> solutions;
vector<string> board(n, string(n, '.'));
backtrack(0, board, solutions, n);
return solutions;
}
private:
void backtrack(int row, vector<string>& board, vector<vector<string>>& solutions, int n) {
if (row == n) {
solutions.push_back(board);
return;
}
for (int col = 0; col < n; col++) {
board[row][col] = 'Q';
if (isValid(board, row, col, n)) {
backtrack(row + 1, board, solutions, n);
}
board[row][col] = '.';
}
}
bool isValid(const vector<string>& board, int row, int col, int n) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'Q') {
if (j == col || abs(row - i) == abs(col - j)) return false;
}
}
}
return true;
}
};
int main() {
Solution sol;
auto res = sol.solveNQueens(4);
for (auto& board : res) {
for (auto& row : board) cout << row << endl;
cout << endl;
}
return 0;
}
Line Notes
vector<string> board(n, string(n, '.'))Initialize board with '.' indicating empty cells
for (int col = 0; col < n; col++)Try placing queen in each column of current row
if (isValid(board, row, col, n))Validate placement before deeper recursion
if (row == n)All queens placed, add current board to solutions
function solveNQueens(n) {
const solutions = [];
const board = Array.from({ length: n }, () => '.'.repeat(n).split(''));
function isValid(row, col) {
for (let i = 0; i < row; i++) {
for (let j = 0; j < n; j++) {
if (board[i][j] === 'Q') {
if (j === col || Math.abs(row - i) === Math.abs(col - j)) return false;
}
}
}
return true;
}
function backtrack(row) {
if (row === n) {
solutions.push(board.map(r => r.join('')));
return;
}
for (let col = 0; col < n; col++) {
board[row][col] = 'Q';
if (isValid(row, col)) {
backtrack(row + 1);
}
board[row][col] = '.';
}
}
backtrack(0);
return solutions;
}
// Example usage:
console.log(solveNQueens(4));
Line Notes
const board = Array.from({ length: n }, () => '.'.repeat(n).split(''))Initialize 2D board with '.' for empty cells
for (let col = 0; col < n; col++)Try placing queen in each column of current row
if (isValid(row, col))Check if current placement is safe before recursing
if (row === n)All queens placed, add current board to solutions
We try placing queens row by row, each row has up to n columns. Checking validity takes O(n) per placement, leading to factorial time in worst case.
💡 For n=4, this means roughly 4! * 4 = 96 operations, which is manageable, but for n=10 it explodes to millions.
Interview Verdict: TLE for large n, but good for understanding
This approach is too slow for big boards but is essential to grasp the problem and backtracking basics.