AlgoTales · Roadmap

N-Queens

Advanced · 12 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

N-Queens asks you to place N chess queens on an N-by-N board so no two attack each other. You place one queen per row, check it is safe, and undo the last queen when you get stuck. It is the classic example of searching with rules that cut off bad choices early.

Practical use cases

  • Web app: Exam hall seating without clashes. A college portal seats students so that two students from the same batch or same subject never sit in the same row, column or diagonal. Place one student per row, check the clash rules, and back up if a row has no free seat. The admin gets a valid seating chart in a second instead of fixing it by hand.
  • Web app: Ad or banner slot placement. A news site has a grid of ad slots, and competing advertisers must not share a row, column or neighbouring diagonal on the page. The system fills row after row and backs up when no slot is safe. Rules like this are easy to state but hard to satisfy by trial. The page can also tell the sales team immediately when no safe layout exists for a given grid, so they know to remove one advertiser rather than waiting for a failure.
  • System: Frequency assignment and constraint solvers. Radio towers close to each other cannot use the same frequency, which is the same kind of "do not conflict" rule. Constraint solvers inside scheduling software use this search style with smart early checks. Each of these tools places one thing at a time, checks the rules at once, and retreats when stuck, which is the same loop you write for the queens board.

The story: Four Queens, No Fights

The school chess club had a puzzle on the notice board: place 4 queens on a 4×4 board so none can capture another. A queen is fierce: she strikes along her row, her column and both diagonals. "Easy," said Aarav, and put queens all along the diagonal. They glared at each other along it. Oops.

Mrs. Sharma gave a hint: "Only one queen fits per row. So go row by row, and for each row find a column that is not attacked." Aarav put a queen at row 1, column 1. In row 2, columns 1 and 2 were attacked, so he took column 3.

But row 3 had no safe square at all! Every column was attacked by one of the two queens. Aarav groaned, then Mrs. Sharma smiled: "That is not failure, it is information. Take the last queen back and try its next column." He moved row 2 to column 4, and later had to move the very first queen too.

After a few steps back he found the answer: columns 2, 4, 1, 3. Four queens, peaceful. This is N-Queens: choose a safe square, explore the next row, and if a row has no safe square, backtrack.

How to spot this problem, and where you need it

You must place items on a grid or schedule so none of them break a conflict rule, and a placement that looks fine early on may fail later.

Signs you need it

  • The problem says "no two ... in the same row, column or diagonal" or "no conflicts" and asks for placements or the count of them.
  • Picking the first valid spot works for a while, then you reach a row with no valid spot and need to undo earlier choices.
  • Checking every possible arrangement is impossibly large, but most arrangements break a rule almost immediately.

Where to use it in a project

  • Seat, room or slot allocation where certain pairs must stay apart.
  • Laying out items on a grid, such as ad slots or dashboard widgets, with exclusion rules.

The solution

Work row by row. In the current row, try each column. For each one, check whether it is attacked by any queen already placed, using the column and both diagonals. If safe, place it and go to the next row. If you reach a row with no safe column, go back one row, lift that queen, and try its next column. Reaching the last row successfully gives a full solution. The early safety check removes huge numbers of hopeless boards.

Payoff: Before: about 4 billion boards to check for 8 queens. After: a few thousand placements, solved in a blink.

Explain it like I am 8

Queens are grumpy: they hate any other queen in their row, column or diagonal line. Put one queen in each row, always on a square nobody is staring at. If you get stuck in a row, pick up the last queen you put down and try a new square for her.

How it works, step by step

  1. Fill the board one row at a time. That already guarantees one queen per row.
  2. For the current row, try every column from left to right.
  3. Safety check: a square is safe if no earlier queen shares its column or either diagonal. Two squares share a diagonal when their row gap equals their column gap.
  4. Choose a safe column (place the queen) and explore the next row.
  5. If the loop ends with no placement, return failure. The caller un-chooses its queen and tries its next column.
  6. When the row index reaches n, every queen is placed: save the solution.

The code in four languages

PHP

<?php
// Count and print solutions of the N-Queens puzzle.
function solveNQueens(int $n): array {
    $solutions = [];
    $cols = [];                               // $cols[row] = column of that row's queen
    $isSafe = function (int $row, int $col) use (&$cols): bool {
        foreach ($cols as $r => $c) {
            if ($c === $col) return false;                        // same column
            if (abs($c - $col) === $row - $r) return false;       // same diagonal
        }
        return true;
    };
    $place = function (int $row) use (&$place, &$solutions, &$cols, $n, $isSafe) {
        if ($row === $n) {                    // every queen placed
            $solutions[] = $cols;
            return;
        }
        for ($col = 0; $col < $n; $col++) {
            if (!$isSafe($row, $col)) continue;
            $cols[$row] = $col;               // choose
            $place($row + 1);                 // explore
            unset($cols[$row]);               // un-choose
        }
    };
    $place(0);
    return $solutions;
}

$sols = solveNQueens(4);
echo count($sols) . " solutions\n";
foreach ($sols[0] as $col) {
    echo str_repeat('. ', $col) . 'Q ' . str_repeat('. ', 3 - $col) . "\n";
}

JavaScript

// Count and print solutions of the N-Queens puzzle.
function solveNQueens(n) {
  const solutions = [];
  const cols = [];                            // cols[row] = column of that row's queen
  function isSafe(row, col) {
    for (let r = 0; r < row; r++) {
      if (cols[r] === col) return false;                       // same column
      if (Math.abs(cols[r] - col) === row - r) return false;   // same diagonal
    }
    return true;
  }
  function place(row) {
    if (row === n) {                          // every queen placed
      solutions.push([...cols]);
      return;
    }
    for (let col = 0; col < n; col++) {
      if (!isSafe(row, col)) continue;
      cols[row] = col;                        // choose
      place(row + 1);                         // explore
      cols.pop();                             // un-choose
    }
  }
  place(0);
  return solutions;
}

const sols = solveNQueens(4);
console.log(sols.length + ' solutions');
for (const col of sols[0]) {
  console.log('. '.repeat(col) + 'Q ' + '. '.repeat(3 - col));
}

Java

import java.util.*;

public class Main {
    // Count and print solutions of the N-Queens puzzle.
    static List<int[]> solveNQueens(int n) {
        List<int[]> solutions = new ArrayList<>();
        place(0, n, new int[n], solutions);
        return solutions;
    }

    // cols[row] = column of that row's queen (only rows before `row` are filled in)
    static boolean isSafe(int[] cols, int row, int col) {
        for (int r = 0; r < row; r++) {
            if (cols[r] == col) return false;                         // same column
            if (Math.abs(cols[r] - col) == row - r) return false;     // same diagonal
        }
        return true;
    }

    static void place(int row, int n, int[] cols, List<int[]> solutions) {
        if (row == n) {                       // every queen placed
            solutions.add(cols.clone());
            return;
        }
        for (int col = 0; col < n; col++) {
            if (!isSafe(cols, row, col)) continue;
            cols[row] = col;                  // choose (un-choose happens by overwriting)
            place(row + 1, n, cols, solutions);   // explore
        }
    }

    public static void main(String[] args) {
        List<int[]> sols = solveNQueens(4);
        System.out.println(sols.size() + " solutions");
        for (int col : sols.get(0)) {
            System.out.println(". ".repeat(col) + "Q " + ". ".repeat(3 - col));
        }
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

// solveNQueens finds all solutions of the N-Queens puzzle.
func solveNQueens(n int) [][]int {
	var solutions [][]int
	var cols []int // cols[row] = column of that row's queen

	isSafe := func(row, col int) bool {
		for r, c := range cols {
			if c == col { // same column
				return false
			}
			if abs(c-col) == row-r { // same diagonal
				return false
			}
		}
		return true
	}

	var place func(row int)
	place = func(row int) {
		if row == n { // every queen placed
			solutions = append(solutions, append([]int(nil), cols...))
			return
		}
		for col := 0; col < n; col++ {
			if !isSafe(row, col) {
				continue
			}
			cols = append(cols, col)  // choose
			place(row + 1)            // explore
			cols = cols[:len(cols)-1] // un-choose
		}
	}
	place(0)
	return solutions
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	sols := solveNQueens(4)
	fmt.Println(len(sols), "solutions")
	for _, col := range sols[0] {
		fmt.Println(strings.Repeat(". ", col) + "Q " + strings.Repeat(". ", 3-col))
	}
}

Time: O(n!) · Extra space: O(n). Each row has fewer safe columns than the last, so the search is far smaller than trying every board, but still grows very fast with n.

Watch out for

  • Testing only rows and columns and forgetting the diagonals.
  • Placing queens anywhere instead of one per row. That makes the search enormous.
  • Not undoing the placement after exploring, so old queens keep blocking squares.

Quick check

  1. Two squares are on the same diagonal when...
    • They have the same column
    • Their rows are both even
    • Their row gap equals their column gap
  2. How many different solutions does the 4×4 board have?
    • 1
    • 4
    • 8
    • 2
  3. What do we do when a row has no safe column?
    • Place a queen anyway
    • Backtrack and move the previous queen
    • Restart from scratch