Resource · Guide or article
N-Queens Problem
Places n non-attacking queens on an n by n board and compares three ways to search for a solution. Good backtracking practice for coding rounds.
Reviewed
Open the original: N-Queens Problem (opens the original site in a new tab)Add to a roadmap
Keep this resource with a roadmap you follow. It appears as your own extra resource; the roadmap's steps don't change and it doesn't count toward your tracked steps.
Source content: English
The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The eight queens puzzle is an example of the more general n queens problem of placing n non-attacking queens on an n×n chessboard, for which solutions exist for all natural numbers n with the exception of n=2 and n=3. For example, following is a solution for 4 Queen problem. The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example following is the output matrix for above 4 queen solution.
PrepKit overview
PrepKit editors wrote and reviewed this overview from the source repository. It is not text from the resource itself.
- Suited to
- The source does not state a level
- Format
- Lesson
What it covers
- States the constraints, notes there are no solutions for n=2 and n=3, and shows a 4x4 answer as a binary matrix
- Pseudocode for the generate-and-test naive method
- Step-by-step pseudocode for column-by-column backtracking
- Bitwise method using leftDiagonal, column and rightDiagonal bitmasks, with worked N=4 and N=8 readings
How to use it
PrepKit study advice, not a claim made by the source.
Code the backtracking version and print every 4x4 solution, then rewrite it with bitmasks and confirm both versions agree on the solution count for n=8.
Scope and limitations
The bitwise section talks about a recursive function that never appears on the page, and its diagram is an external image. No complexity figures are given.
Access and format
README on GitHub in trekhleb/javascript-algorithms (MIT). English, free to read.
Reviewed by PrepKit on Oct 2, 2026. Listing source commit: 85293e3e2b88
Evidence behind this overview
- src/algorithms/uncategorized/n-queens/README.md
Pages that include this
Get the PrepKit newsletter
Optional. You don't need it to use PrepKit.