A real-time journey of building a smart N-Queens solver from scratch using Python and AI search heuristics.
๐ Day 1: Classic Backtracking Solver
In this journey, we began solving the classic N-Queens Problem using the backtracking search algorithm. The goal: place N queens on an NรN chessboard such that no two queens threaten each other โ meaning no two queens can be in the same row, column, or diagonal.
๐ What We Implemented
- Designed a
Boardclass to represent the state of the chessboard. - Implemented
is_safe()to check queen conflicts. - Wrote a clean
backtrack()function to explore solutions recursively. - Displayed a visual layout of the solution in the terminal using
display().
โ๏ธ Analogy: The Queen's Banquet
Imagine organizing a royal banquet for N queens. Each queen demands a private table without proximity conflicts. You try placing them one at a time, but if one future queen can't find a suitable seat, you must reshuffle. This is the essence of backtracking.
๐ง Concepts Practiced
- Recursive search (DFS style)
- State validation and pruning
- Backtracking to previous state when hitting a dead-end
๐ Result
Successfully solved the 8-Queens problem with all 92 valid solutions using Python. The program prints one of the valid solutions as a visual board layout:
. Q . . . . . .
. . . Q . . . .
. . . . . Q . .
. . . . . . . Q
Q . . . . . . .
. . Q . . . . .
. . . . Q . . .
. . . . . . Q .
This marks our base โ solving with logic, not luck. Next, weโll explore heuristics to make the solver faster and smarter.
๐ช Analogy: Least Constraining Value (LCV)
Imagine you're a banquet planner, seating royal queens at a long dinner table. You're placing them one by one. Every time you assign a seat to a queen, she uses her influence to block several nearby chairs.
Some seats cause more drama than others. If you place a queen at seat 3, it might block five seats for future queens. But placing her at seat 7 only blocks two.
So what do you do?
You seat her where she causes the least trouble โ that's the Least Constraining Value.
- Goal: Reduce future conflicts.
- Strategy: Try the column (seat) that leaves the most options for upcoming queens.
- Result: Fewer backtracks, faster solutions.
It's like seating a picky queen far from others so the rest of the banquet goes smoothly. You're not solving for just now โ you're planning ahead.
โ๏ธ Day 3: Implementing MRV in Code
Code, explanation, before/after comparison...
โ๏ธ Day 4: Implementing LCV in Code
Code, optimization result, graphs if any...
๐ Reflection & Takeaways
Real-world value, AI connection, GitHub repo, next ideas...