146. Leetcode 51. N 皇后 (回溯算法-棋盘问题)
生活随笔
收集整理的這篇文章主要介紹了
146. Leetcode 51. N 皇后 (回溯算法-棋盘问题)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
class Solution:def solveNQueens(self, n: int) -> List[List[str]]:if not n: return []res = []board = [["." for _ in range(n)] for _ in range(n)]def isValid(board,row,col):# 同一列for i in range(len(board)):if board[i][col] == 'Q':return False# 左上角i = row - 1j = col - 1while i >= 0 and j >= 0:if board[i][j] == 'Q':return Falsei -= 1j -= 1# 右上角i = row - 1j = col + 1while i >= 0 and j < len(board):if board[i][j] == 'Q':return Falsei -= 1j += 1return Truedef dfs(board, row, n):if row == n:temp_res = []for temp in board:temp_str = "".join(temp)temp_res.append(temp_str)res.append(temp_res)for col in range(n):if not isValid(board, row, col):continueboard[row][col] = 'Q'dfs(board, row + 1, n)board[row][col] = '.'dfs(board, 0, n)return res
?
總結(jié)
以上是生活随笔為你收集整理的146. Leetcode 51. N 皇后 (回溯算法-棋盘问题)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 143. Leetcode 78. 子集
- 下一篇: 148. Leetcode 455. 分