class Solution(object): def __init__(self): self.queenList = [] self.result = [] self.charList = [] def solveNQueens(self, n): for i in range(0,n): self.charList.append(".") self.currLayer(0,n) return self.result """ :type n: int :rtype: List[List[str]] """ def currLayer(self, x, n): if(x==n): result = [] for queen in self.queenList: self.charList[queen[1]] = "Q" result.append("".join(self.charList)) self.charList[queen[1]] = "." self.result.append(result) return for y in range(0,n): temp = (x,y) if(self.ableToPutDown(temp)): self.queenList.append(temp) self.currLayer(x+1,n) self.queenList.pop() def ableToPutDown(self, temp): for queen in self.queenList: if( queen[1] == temp[1] ):#same col return False elif( abs(queen[0]-temp[0]) == abs(queen[1]-temp[1]) ):#same diagonal return False return True
原文:http://my.oschina.net/joshuashaw/blog/503991