ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

N-Queens Problem Solver (Backtracking)

Kotlin

Goal -- WPM

Ready
Exercise Algorithm Area
1import kotlin.math.abs
2
3class NQueensSolver {
4private lateinit var board: Array<IntArray>
5private lateinit var solutions: MutableList<List<String>>
6private var n: Int = 0
7
8fun solveNQueens(n: Int): List<List<String>> {
9this.n = n
10board = Array(n) { IntArray(n) { 0 } } // 0: empty, 1: queen
11solutions = mutableListOf()
12solve(0)
13return solutions
14}
15
16private fun solve(row: Int) {
17// Base case: If all queens are placed, add the current board configuration to solutions
18if (row == n) {
19solutions.add(formatBoard())
20return
21}
22
23// Try placing a queen in each column of the current row
24for (col in 0 until n) {
25if (isSafe(row, col)) {
26// Place queen
27board[row][col] = 1
28
29// Recur to place the rest of the queens
30solve(row + 1)
31
32// Backtrack: Remove queen (reset the cell) for exploring other possibilities
33board[row][col] = 0
34}
35}
36}
37
38// Check if it's safe to place a queen at board[row][col]
39private fun isSafe(row: Int, col: Int): Boolean {
40// Check this column on upper rows
41for (i in 0 until row) {
42if (board[i][col] == 1) {
43return false
44}
45}
46
47// Check upper diagonal on left side
48for (i in row - 1 downTo 0) {
49val j = col - (row - i)
50if (j >= 0 && board[i][j] == 1) {
51return false
52}
53}
54
55// Check upper diagonal on right side
56for (i in row - 1 downTo 0) {
57val j = col + (row - i)
58if (j < n && board[i][j] == 1) {
59return false
60}
61}
62
63// If no conflicts, it's safe to place a queen
64return true
65}
66
67// Helper function to format the board into a list of strings
68private fun formatBoard(): List<String> {
69val formatted = mutableListOf<String>()
70for (i in 0 until n) {
71val rowString = StringBuilder()
72for (j in 0 until n) {
73rowString.append(if (board[i][j] == 1) 'Q' else '.')
74}
75formatted.add(rowString.toString())
76}
77return formatted
78}
79}
Algorithm description viewbox

N-Queens Problem Solver (Backtracking)

Algorithm description:

This class provides a solution to the N-Queens problem using a backtracking algorithm. The N-Queens puzzle is the challenge of placing N non-attacking queens on an N×N chessboard. This means no two queens should share the same row, column, or diagonal. The algorithm explores possible placements recursively, pruning branches that lead to invalid configurations. This is a fundamental problem in computer science for understanding recursion and constraint satisfaction.

Algorithm explanation:

The N-Queens problem is solved using a recursive backtracking approach. The `solveNQueens` function initializes the board and a list to store solutions, then calls the recursive `solve` function starting from the first row. The `solve` function attempts to place a queen in each column of the current `row`. Before placing a queen, it calls `isSafe` to check if the position is valid (i.e., not attacked by any previously placed queens). If a position is safe, a queen is placed, and the function recursively calls itself for the next row (`row + 1`). If placing a queen in a certain column does not lead to a solution, the algorithm backtracks by removing the queen (resetting the cell to empty) and trying the next column. The base case for the recursion is when all `n` queens have been successfully placed (`row == n`), at which point the current board configuration is formatted and added to the list of solutions. The `isSafe` function checks for conflicts in the same column, and both upper diagonals. The time complexity is roughly O(N!), as in the worst case, it might explore all permutations, though pruning significantly reduces the actual search space. The space complexity is O(N^2) for the board and O(N) for the recursion depth, plus space for storing solutions. Edge cases like N=1 are implicitly handled. The correctness is guaranteed by the exhaustive search and pruning of invalid states.

Pseudocode:

class NQueensSolver:
  board = N x N grid, initialized to empty
  solutions = empty list
  N = board size

  function solveNQueens(N):
    initialize board and solutions
    call solve(0)
    return solutions

  function solve(row):
    if row == N:
      add current board configuration to solutions
      return

    for col from 0 to N-1:
      if isSafe(row, col):
        place queen at board[row][col]
        solve(row + 1)
        remove queen from board[row][col] // backtrack

  function isSafe(row, col):
    // check column above
    // check upper-left diagonal
    // check upper-right diagonal
    return true if no conflicts, false otherwise

  function formatBoard():
    // convert board grid to list of strings
    return formatted board