994. 腐烂的橘子,207. 课程表, 208.实现 Trie (前缀树)
994. 腐烂的橘子
思路:
- 用队列+迭代法的思路来进行广搜,记录每一轮广搜的结果和记录广搜的次数
- 对特殊情况进行额外判断
手撕Code
from collections import dequeclass Solution:def orangesRotting(self, grid: List[List[int]]) -> int:row = len(grid)line = len(grid[0])self.directions = [[-1,0], [1,0], [0,1], [0,-1]]self.visited = [[False] * line for _ in range(row)]self.count = 0stack = deque() ## 广搜,用队列存储遍历结果zero_count, one_count = 0, 0for i in range(row):for j in range(line):if grid[i][j] == 0:zero_count += 1 ## 没有橘子的个数if grid[i][j] == 1:one_count += 1 ## 有橘子的个数if grid[i][j] == 2:stack.append((i,j)) ### 将腐烂的橘子位置推入队列中if zero_count == row * line: ### 压根就没有橘子return 0if one_count == row * line: ### 全是新鲜的橘子,没有腐烂的return -1self.bfs(grid, stack)for i in range(row):if 1 in grid[i]:return -1else:return self.count - 1def bfs(self, grid, stack):row = len(grid)line = len(grid[0])while stack:size = len(stack)while size: ### 进行一次广搜cur_x, cur_y = stack.popleft()grid[cur_x][cur_y] = 2 ### 将当前新鲜的橘子改为腐烂状态for x_offset, y_offset in self.directions:next_x = cur_x + x_offsetnext_y = cur_y + y_offsetif next_x < 0 or next_x >= row or next_y < 0 or next_y >= line:continueif grid[next_x][next_y] == 1 and self.visited[next_x][next_y] == False:self.visited[next_x][next_y] = Truestack.append((next_x, next_y))size -= 1self.count += 1
207. 课程表
思路:
- 本质上是让你判断一个有向图是否存在环状的一个路径
解决方法:
- 邻接表+深度遍历,判断深度遍历的终点会不会等于起点,如果是则存在环。
手撕Code
from collections import defaultdictclass Solution:def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:### 思路:### 1. 这个矩阵不能存在对角线对称的关系。 即两个关系是双向的row = line = numCoursesmatrix_map = defaultdict(list)for node in prerequisites:cur_x, cur_y = node[0], node[1]matrix_map[cur_x].append(cur_y)if cur_y in matrix_map and cur_x in matrix_map[cur_y]: ### 直接的双向关系return Falsefor begin in matrix_map: ### 判断从每个起点出发能不能还走回起点for cur_node in matrix_map[begin]:if self.dfs(matrix_map, begin, cur_node): ### 表明存在环状的逻辑路径return Falsereturn Truedef dfs(self, matrix_map, begin, cur_node, visited = None): ### 对当前cur_node进行深度遍历## 本质还是回溯算法if visited is None: ### 记录遍历过的点visited = set()visited.add(cur_node) ### 将cur_node标记为访问过if begin == cur_node:return Trueif cur_node not in matrix_map: ### cur_node是终点,它不能再往下dfs了return Falsefor next_node in matrix_map[cur_node]:if next_node not in visited:if self.dfs(matrix_map, begin, next_node, visited): ### 这里一旦判断是True了后就得返回,否则后续的会进行覆盖return Truereturn False
解决方法2:
- 拓扑排序也是判断有向图是否存在环的经典解法。
- 具体实现参考https://blog.csdn.net/weixin_59234335/article/details/150532800?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522183300fb43c7e9143121307800cde134%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=183300fb43c7e9143121307800cde134&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-150532800-null-null.nonecase&utm_term=%E6%8B%93%E6%89%91%E6%8E%92%E5%BA%8F&spm=1018.2226.3001.4450
- 实现方式:队列+迭代法遍历,队列记录每个入度为0的节点,迭代法遍历去对每个入度为0的节点进行操作(跟广搜的实现方式一样)。一个result数组存储每次删除的入度为0的节点,如果result数组等于节点数目,则证明图是不成环的。
Code
from collections import defaultdict, dequeclass Solution:def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:### 拓扑排序思路### 每次删除入度为0的节点,和其连接的边,并将该节点添加到队列中### 如果队列的长度等于节点的数目,则证明这个有向图不存在环row = line = numCoursesmatrix_map = defaultdict(list)in_edge = [0] * line ### 记录每个节点的入度for node in prerequisites:next_node, pre_node = node[0], node[1]matrix_map[pre_node].append(next_node)in_edge[next_node] += 1 ### 被指向的节点入度+1queue = deque() ### 队列,记录删除的每个节点, 对该队列进行迭代result = []for i in range(len(in_edge)):if in_edge[i] == 0:queue.append(i) ### step1: 将该入度为0的节点添加到队列中while queue: ### step2:对每个入度为0的节点进行操作cur_node = queue.popleft()result.append(cur_node) ### 记录每个被删除的节点if cur_node in matrix_map:for next_node in matrix_map[cur_node]:in_edge[next_node] -= 1 ### step3: 删除入度为0的节点指向的节点的入度值if in_edge[next_node] == 0:queue.append(next_node) ### 新的入度为0的节点if len(result) == numCourses:return Trueelse:return False