The Eight Queens Problem

From Daily Coding Problem, here comes a classic problem:

This problem was asked by Microsoft.
You have an N by N board. Write a function that, given N, returns the number of possible arrangements of the board where N queens can be placed on the board without threatening each other, i.e. no two queens share the same row, column, or diagonal.

This is a well-known CS problem, with a vast literature: https://www.bing.com/search?q=eight+queens+problem&qs=AS&pq=eight+queens&sc=6-12&cvid=909319BFEDC54FB4AACA2EB2B1274ACB&FORM=QBLH&sp=1

And I've written about this problem before, just search for "super queens" in my blog.

Problem is actually simpler than it looks, at least the version that generates all the solutions - there is another one that uses DP, but I don't know the details of that one.

For the traditional problem:

  • Use backtracking
  • Have 4 hash tables which will indicate, respectively:
    • Whether a row has been taken by a queen
    • Or a column
    • Or a diagonal in the form row + column
    • Or a diagonal in the form row - column

Cheers, Marcelo.

Comments

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval