本文主要是介绍Day30代码随想录回溯part06:332.重新安排行程、451. N皇后、37. 解数独,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
332.重新安排行程(这道题没有自己完成)
回溯 使用字典
```python
class Solution:def findItinerary(self, tickets: List[List[str]]) -> List[str]:self.adj = {}# sort by the destination alphabetically# 根据航班每一站的重点字母顺序排序tickets.sort(key=lambda x:x[1])# get all possible connection for each destination# 罗列每一站的下一个可选项for u,v in tickets:if u in self.adj: self.adj[u].append(v)else: self.adj[u] = [v]# 从JFK出发self.result = []self.dfs("JFK") # start with JFKreturn self.result[::-1] # reverse to get the resultdef dfs(self, s):# if depart city has flight and the flight can go to another citywhile s in self.adj and len(self.adj[s]) > 0:# 找到s能到哪里,选能到的第一个机场v = self.adj[s][0] # we go to the 1 choice of the city# 在之后的可选项机场中去掉这个机场self.adj[s].pop(0) # get rid of this choice since we used it# 从当前的新出发点开始self.dfs(v) # we start from the new airportself.result.append(s) # after append, it will back track to last node, thus the result list is in reversed order
51. N皇后
leetcode题目链接:51. N 皇后 - 力扣(LeetCode)
不能同行、不能同列、不能同斜线
回溯的模板:
void backtracking(参数) {if (终止条件) {存放结果;return;}for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) {处理节点;backtracking(路径,选择列表); // 递归回溯,撤销处理结果}
}
传入参数:当前所在行数row、棋盘当前状态;全局变量result和path
终止条件:遍历到最后一行
单层递归逻辑:逐行遍历,在每一行中逐个位置找寻是不是合法位置
巧思:这里只需要检查45度和135度而不用检查180度和-45度是因为这是逐行遍历的,所以下面是没有值的
class Solution:def __init__(self):self.res = []def isValid(self, table, row, col, n):for i in range(n):if table[i][col] == 'Q':return False# 检查45度i, j = row-1, col-1while i>=0 and j>=0:if table[i][j] == 'Q':return Falsei-=1j-=1i, j = row-1, col+1while i>=0 and n>j>=0:if table[i][j] == 'Q':return Falsei-=1j+=1return Truedef backtracking(self, table, row, n):if row == n:# print([''.join(table[i]) for i in range(n)])self.res.append([''.join(table[i]) for i in range(n)])returnfor i in range(n):if self.isValid(table, row, i, n):table[row][i] = 'Q'# print(row, i, table)self.backtracking(table, row+1, n)table[row][i] = '.'def solveNQueens(self, n: int) -> List[List[str]]:table = [['.']*n for i in range(n)]self.backtracking(table, 0, n)return self.res
37. 解数独
leetcode题目链接:37. 解数独 - 力扣(LeetCode)
本题的重点是一个二维递归,求一个数独的结果就可以了,所以返回值使用的是bool(找到一个就立刻返回),之前搜索所有集合的是使用的void
伪代码:
bool backtracking(board){for(i=0;i<n;i++){for(j=0;j<n;j++){if(board[i][j] == '.'){for(k= '1'; k<='9'; k++){if isvalid(i, j, k, board){board[i][j]=k;bool result=backtracking(board);if result == True: return true//回溯board[i][j] = '.'}}}}}
}
python版本:
class Solution:def isValid(self,board, row, col, num):for i in range(len(board)): # 行if board[i][col] == str(num):return Falsefor i in range(len(board[0])): # 列if board[row][i] == str(num):return Falserindex = row//3colindex = col//3for i in range(3*rindex, 3*(rindex+1)):for j in range(3*colindex, 3*(colindex+1)):if board[i][j] == str(num):return Falsereturn Truedef backtracking(self, board):for i in range(len(board)):for j in range(len(board[0])): # 第二个维度的长度if board[i][j] !='.': continueelse:for k in range(1, 10): # 填数if self.isValid(board, i, j, k):board[i][j] = str(k)if self.backtracking(board): return Trueboard[i][j] = '.'# 若数字1-9都不能成功填入空格,返回False无解return Falsereturn Truedef solveSudoku(self, board: List[List[str]]) -> None:"""Do not return anything, modify board in-place instead."""self.backtracking(board)
这篇关于Day30代码随想录回溯part06:332.重新安排行程、451. N皇后、37. 解数独的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!