1. N 皇后
題目連結:https://leetcode.cn/problems/n-queens/
給定一個整數 n ,返回所有不同的 n 皇后問題 的解決方案,方案中 'Q' 和 '.' 分別代表了皇后和空位。
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def is_valid(board, row, col):
for i in range(row):
if board[i][col] == 'Q':
return False
if col - (row - i) >= 0 and board[i][col - (row - i)] == 'Q':
return False
if col + (row - i) < n and board[i][col + (row - i)] == 'Q':
return False
return True
def backtrack(board, row):
if row == n:
res.append([''.join(row) for row in board])
return
for col in range(n):
if is_valid(board, row, col):
board[row][col] = 'Q'
backtrack(board, row + 1)
board[row][col] = '.'
board = [['.' for _ in range(n)] for _ in range(n)]
res = []
backtrack(board, 0)
return res
2. N 皇后 II
題目連結:https://leetcode.cn/problems/n-queens-ii/
給定一個整數 n ,返回 n 皇后問題 不同的解決方案的數量。
class Solution:
def totalNQueens(self, n: int) -> int:
def is_valid(board, row, col):
for i in range(row):
if board[i][col] == 'Q':
return False
if col - (row - i) >= 0 and board[i][col - (row - i)] == 'Q':
return False
if col + (row - i) < n and board[i][col + (row - i)] == 'Q':
return False
return True
def backtrack(board, row):
if row == n:
return 1
count = 0
for col in range(n):
if is_valid(board, row, col):
board[row][col] = 'Q'
count += backtrack(board, row + 1)
board[row][col] = '.'
return count
board = [['.' for _ in range(n)] for _ in range(n)]
return backtrack(board, 0)