Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.
For example, There exist two distinct solutions to the 4-queens puzzle:
class(object): defcheck(self, path, y): j = len(path) for i, x in enumerate(path): if x == y or y - j == x - i or y + j == x + i: returnFalse returnTrue
defdfs(self, n, path, rs): if n == len(path): rs.append(path[:]) return for i in xrange(n): if self.check(path, i): path.append(i) self.dfs(n, path, rs) path.pop()
deflistToMaze(self, lst): rs = [] n = len(lst) for x in lst: rs.append('.' * x + 'Q' + '.' * (n - x - 1)) return rs
defsolveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ if n == 0: return0 rs = [] path = [] self.dfs(n, path, rs) return [self.listToMaze(x) for x in rs]
近期评论