您的位置:首页 > 产品设计 > UI/UE

LeetCode 51 N-Queens

2018-01-10 15:08 507 查看

题目

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.



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:

[

[“.Q..”, // Solution 1

“…Q”,

“Q…”,

“..Q.”],

[“..Q.”, // Solution 2

“Q…”,

“…Q”,

“.Q..”]

]

思路

DFS经典问题。

难点是判断斜线条件。当两个点在同一条斜线上时,i1+j1==i2+j2

代码

class Solution:

def __init__(self):
self.res = []

def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
cols = [0 for i in range(n)]
flag = [0 for i in range(n)]
flag1 = [0 for i in range(2 * n - 1)]
flag2 = [0 for i in range(2 * n - 1)]
for i in range(n):
cols[0] = i
flag[i] = 1
flag1[0 + i] = 1
flag2[0 - i + n - 1] = 1
self.dfs(1, cols, flag, flag1, flag2, n)
flag[i] = 0
flag1[0 + i] = 0
flag2[0 - i + n - 1] = 0
return self.res

def dfs(self, col, cols, flag, flag1, flag2, n):
if col == n:
self.res.append(self.output(cols))
return
for i in range(n):
if flag[i] == 0 and flag1[col + i] == 0 and flag2[col - i + n - 1] == 0:
cols[col] = i
flag[i] = 1
flag1[col + i] = 1
flag2[col - i + n - 1] = 1
self.dfs(col + 1, cols, flag, flag1, flag2, n)
flag[i] = 0
flag1[col + i] = 0
flag2[col - i + n - 1] = 0

def output(self, cols):
res = []
for i in range(len(cols)):
line = ''
for j in range(len(cols)):
if j == cols[i]:
line += 'Q'
else:
line += '.'
res.append(line)
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: