N皇后問題
n皇后問題是將n個皇后放置在n*n的棋盤上,皇后彼此之間不能相互攻擊。
給定一個整數n,返回所有不同的n皇后問題的解決方案。
每個解決方案包含一個明確的n皇后放置佈局,其中“Q”和“.”分別表示一個女王和一個空位置。
樣例
對於4皇后問題存在兩種解決的方案:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
思路
由於每行只能有一個皇后,第一行 有N種可能,從一行一列開始 如果一行一列可以放置皇后 則找到下一行第一個能放置皇后的列。如果下一行 沒有符合條件的列,就返回上一行找到下一個可以放置皇后的列。遍歷的行數 == N 則獲得一次 結果。如果在第一行也找不到能放置皇后的列 則查找結束。
實現
循環實現
class Solution:
"""
Get all distinct N-Queen solutions
@param n: The number of queens
@return: All distinct solutions
"""
def solveNQueens(self, n):
# write your code here
#每一行和每一列只能有一個皇后 而且必定有一個皇后
n = int(n)
result = []
col = [-1]*n
k = 0
#row
while k>=0:
#查看下一列
col[k] = col[k]+1
while col[k]<n and not self.judgePlace(k,col):
#col
col[k] += 1
if col[k]<n:
#獲得一次解
if k == n-1:
empty = ['.'*n for i in range(0,n)]
for i in range(0,n):
temp = list(empty[i])
temp[col[i]] = 'Q'
empty[i] = ''.join(temp)
result.append(empty)
#判斷下一行
else:
k +=1
#清除殘留數據
col[k] = -1
#沒有找到結果回溯
else:
k -= 1
return result
def judgePlace(self,k,col):
for i in range(0,k):
if col[i] == col[k] or (abs(col[k]-col[i]) == abs(k - i)):
return False
return True
遞歸實現
class Solution:
"""
Get all distinct N-Queen solutions
@param n: The number of queens
@return: All distinct solutions
"""
def solveNQueens(self, n):
n = int(n)
result = []
record = [0]*(n+1)
self.findResult(result,n,1,1,record)
return result
def findResult(self,result,total,row,col,record):
if row == 0:
return result
record[row] = col
while record[row]<=total and not self.judgePlace(row,record):
record[row] += 1
#回溯
if record[row]>total:
row -= 1
newCol = record[row] + 1
self.findResult(result,total,row,newCol,record)
else:
if row == total:
empty = ['.'*total for i in range(0,total)]
for i in range(0,total):
temp = list(empty[i])
temp[record[i+1]-1] = 'Q'
empty[i] = ''.join(temp)
result.append(empty)
#回溯
row -= 1
newCol = record[row] + 1
self.findResult(result,total,row,newCol,record)
else:
row += 1
self.findResult(result,total,row,1,record)
def judgePlace(self,row,col):
for i in range(1,row):
if col[i] == col[row] or (abs(col[row]-col[i]) == abs(row - i)):
return False
return True