Welcome, guest | Sign In | My Account | Store | Cart

This relatively simple program solves by iteration the classic 8 queens chess problem. For those unfamiliar, the challenge is to find the number of ways it's possible arrange 8 queens on a chess board so that none can capture any other in one move. There's some wierd mathmatical proof of this, but this simple Python program demonstrates recursive iteration through many, (8^8), possible possibilities in the most efficient manor possible. The code itself was written for clarity and speed by someone relatively new to Python, so it should be pretty easy to understand.

Python, 26 lines
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26``` ```def Permute(queens, row): for i in range(8): queens[row] = i if Fine(queens, row): if row == 7: print(queens) globals()["solutions"] = globals()["solutions"] + 1 else: Permute(queens, row+1) def Fine(queens, row): c = 0 derga = True for i in range(row): c, cur, oth = c+1, queens[row], queens[row-i-1] if (cur == oth) or (cur-c == oth) or (cur+c == oth): derga = False break return(derga) globals()["solutions"] = 0 queens = [20, 20, 20, 20, 20, 20, 20, 20] for i in range(8): queens[0] = i Permute(queens, 1) print(solutions) ```

WHY DO IT? For programming experience, and to solve a simple looking but fun problem. :D

WHY THIS SOLUTION? Because the mathematical proof for this is annoyingly long and overcomplicated, and because programming's fun.

ISSUES: None

ALTERNATIVES: Try re-writing this program for different size boards and different numbers of queens. :D

HELP: You'll need to understand arrays, loops and multiple assignment. As I said before, it's a pretty simple program!

 Created by Calder Coalson on Mon, 26 Mar 2007 (PSF)

Required Modules

• (none specified)