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
相关文章推荐
- [leetcode] 51.N-Queens
- LeetCode—51.N-Queens
- Leetcode 51 52 N-Queens
- LeetCode51 N-Queens
- Leetcode 51. N-Queens
- LeetCode-51.N-Queens
- n皇后问题leetcode-51. N-Queens
- leetcode 51. N-Queens
- 51. N-Queens Leetcode Python
- leetcode hard模式专杀之51. N-Queens
- LeetCode 51.N-Queens
- LeetCode-51&52.N-Queens
- Leetcode 51. N-Queens && 52. N-Queens II(Hard)
- LeetCode - 51. N-Queens
- leetcode(51):N-Queens
- leetcode 51. N-Queens
- leetcode 51. N-Queens
- Leetcode||51. N-Queens
- 2017.11.8 LeetCode N皇后问题 - 51. N-Queens - 52....
- LeetCode 51. N-Queens