代码随想录刷题第三十天
重新安排行程 (LC 332)
题目思路:
代码实现:
class Solution:
def __init__(self):
self.path = ['JFK']
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
# targets is a dictionary of list which stores the mapping between 出发地和目的地
targets = defaultdict(list)
for ticket in tickets:
targets[ticket[0]].append(ticket[1])
# sort the values of the dictionary
for destination in targets.values():
destination.sort()
self.backtracking(targets, len(tickets))
return self.path
def backtracking(self, targets, ticketnum):
if len(self.path) == ticketnum+1:
return True
cur = self.path[-1]
for i, airport in enumerate(targets[cur]):
targets[cur].pop(i)
self.path.append(airport)
nextbool = self.backtracking(targets, ticketnum)
if nextbool:
return True
self.path.pop()
targets[cur].insert(i, airport)
return False
N皇后 (LC 51)
题目思路:
代码实现:
class Solution:
def __init__(self):
self.result = []
def solveNQueens(self, n: int) -> List[List[str]]:
path = ['.'*n for _ in range(n)]
self.backtracking(n, 0, path)
return self.result
def backtracking(self, n, row, path):
if row == n:
self.result.append(path[:])
return
for col in range(n):
if self.isvalid(row, col, n, path):
path[row] = path[row][:col] + 'Q' + path[row][col+1:]
self.backtracking(n, row+1, path)
path[row] = path[row][:col] + '.' + path[row][col+1:]
def isvalid(self, row, col, n, path):
#检查列
for i in range(row):
if path[i][col] == 'Q':
return False
# 检查135度
i = row-1
j = col-1
while i>=0 and j>=0:
if path[i][j] == 'Q':
return False
i-=1
j-=1
# 检查45度
i = row-1
j = col+1
while i>=0 and j<n:
if path[i][j] == 'Q':
return False
i-=1
j+=1
return True
解数独 (LC 37)
题目思路:
代码实现:
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
mybool = self.backtracking(board)
return mybool
def backtracking(self, board):
for i in range(9):
for j in range(9):
if board[i][j] !='.':
continue
for k in range(1,10):
if self.isvalid(board, i, j, k):
board[i] = board[i][:j]+[str(k)]+board[i][j+1:]
nextbool = self.backtracking(board)
if nextbool:
return True
board[i] = board[i][:j]+['.']+board[i][j+1:]
return False
return True
def isvalid(self, board, i, j, k):
for row in range(9):
if board[row][j] == str(k):
return False
for col in range(9):
if board[i][col] == str(k):
return False
for row in range(3*(i//3), 3*(i//3)+3):
for col in range(3*(j//3), 3*(j//3)+3):
if board[row][col] == str(k):
return False
return True