#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
N-Queens
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
'''
class Solution(object):
def __check(self,result,start_index,next_val):
for index,val in enumerate(result[:start_index]):
if (val == next_val) or (abs(index - start_index) == abs(val - next_val)): #将不符合N皇后规则的去掉
return False
return True
def __solveNQueens(self,n,result,start_index,ret,fmt):
if start_index == n:
tmp = []
for val in result:
fmt[val] = 'Q'
tmp.append(''.join(fmt))
fmt[val] = '.'
ret.append(tmp)
else:
#index代表行数,val代表列数
for i in range(n):
if self.__check(result,start_index,i) == True:
result[start_index] = i
self.__solveNQueens(n,result,start_index + 1,ret,fmt)
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
if n == 1:
return [['Q']]
if n < 4:
return []
ret = []
fmt = ["."] * n
self.__solveNQueens(n,[0]*n,0,ret,fmt)
return ret
if __name__ == "__main__":
s = Solution()
for i in s.solveNQueens(4):
for j in i:
print j
print "=========="
54 leetcode - N-Queens
最新推荐文章于 2025-01-18 19:45:42 发布