目录
学习目标
- 332.重新安排行程
- 51. N皇后
- 37. 解数独
- 总结
学习内容
332.重新安排行程
332. 重新安排行程 - 力扣(LeetCode)
https://leetcode.cn/problems/reconstruct-itinerary/
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
dic = {}
n = len(tickets)
for item in tickets:
if item[0] not in dic:
dic[item[0]] = [item[1]]
else:
dic[item[0]].append(item[1])
for values in dic.values():
values.sort()
res = []
def dfs(start,n):
res.append(start)
if n==0:
return True
if start not in dic:return False
for i in range(len(dic[start])):
end = dic[start][i]
n-=1
dic[start].pop(i)
if dfs(end,n):
return True
res.pop()
n+=1
dic[start].insert(i,end)
dfs("JFK",n)
return res
51. N皇后
51. N 皇后 - 力扣(LeetCode)
https://leetcode.cn/problems/n-queens/
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
res = []
tmp = [["."]*n for _ in range(n)]
def dfs(i):
if i==n:
ans = []
for j in range(n):
ans.append("".join(tmp[j]))
res.append(ans.copy())
return
for j in range(n):
if is_could(i,j):
tmp[i][j]="Q"
dfs(i+1)
tmp[i][j]="."
def is_could(i,j):
for k in range(0,i):
if tmp[k][j]=="Q":
return False
# 左上
k = 1
while j-k>=0 and i-k>=0:
if tmp[i-k][j-k]=="Q":
return False
k+=1
# 右上
k = 1
while j+k<n and i-k>=0:
if tmp[i-k][j+k]=="Q":
return False
k+=1
return True
dfs(0)
return res
37. 解数独
37. 解数独 - 力扣(LeetCode)
https://leetcode.cn/problems/sudoku-solver/
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def dfs(board):
for i in range(9):
for j in range(9):
if board[i][j]==".":
for k in range(1,10):
if is_could(i,j,str(k)):
board[i][j]=str(k)
if dfs(board):
return True
board[i][j]="."
return False
return True
def is_could(i,j,k):
for z in range(9):
if board[i][z]==k:
return False
for z in range(9):
if board[z][j]==k:
return False
for x in range(i//3*3,i//3*3+3):
for y in range(j//3*3,j//3*3+3):
if board[x][y]==k:
return False
return True
dfs(board)
总结