numQueens = 8 solutions = [] def printBoard(placed): for c in placed: r = ['. '] * 8 r[c] = 'o ' print ''.join(r) print '-' * 16 def isDiagonal(r1, c1, r2, c2): d = r2 - r1 # Always positive since r1 is always less. return c2 - d == c1 or c2 + d == c1 def isInvalid(placed, c): for o_r, o_c in enumerate(placed): if isDiagonal(o_r, o_c, len(placed), c): return True def placeQueen(valid, placed): if len(placed) == numQueens: return solutions.append(placed[:]) for i, c in enumerate(valid): if isInvalid(placed, c): continue placed.append(c) placeQueen(valid[:i] + valid[i+1:], placed) placed.pop() placeQueen(range(8), []) for solution in solutions: printBoard(solution)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question