Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
n-queens.py 2.00 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-12-30 21:04 +08:00 . remove semicolons
# Time: O(n!)
# Space: O(n)
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def dfs(curr, cols, main_diag, anti_diag, result):
row, n = len(curr), len(cols)
if row == n:
result.append(map(lambda x: '.'*x + "Q" + '.'*(n-x-1), curr))
return
for i in xrange(n):
if cols[i] or main_diag[row+i] or anti_diag[row-i+n]:
continue
cols[i] = main_diag[row+i] = anti_diag[row-i+n] = True
curr.append(i)
dfs(curr, cols, main_diag, anti_diag, result)
curr.pop()
cols[i] = main_diag[row+i] = anti_diag[row-i+n] = False
result = []
cols, main_diag, anti_diag = [False]*n, [False]*(2*n), [False]*(2*n)
dfs([], cols, main_diag, anti_diag, result)
return result
# For any point (x,y), if we want the new point (p,q) don't share the same row, column, or diagonal.
# then there must have ```p+q != x+y``` and ```p-q!= x-y```
# the former focus on eliminate 'left bottom right top' diagonal
# the latter focus on eliminate 'left top right bottom' diagonal
# - col_per_row: the list of column index per row
# - cur_row:current row we are seraching for valid column
# - xy_diff:the list of x-y
# - xy_sum:the list of x+y
class Solution2(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def dfs(col_per_row, xy_diff, xy_sum):
cur_row = len(col_per_row)
if cur_row == n:
ress.append(col_per_row)
for col in range(n):
if col not in col_per_row and cur_row-col not in xy_diff and cur_row+col not in xy_sum:
dfs(col_per_row+[col], xy_diff+[cur_row-col], xy_sum+[cur_row+col])
ress = []
dfs([], [], [])
return [['.'*i + 'Q' + '.'*(n-i-1) for i in res] for res in ress]
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助