一、深度遍历
1.员工的重要性 leetcode 690
思路:深度遍历
""" # Employee info class Employee: def __init__(self, id, importance, subordinates): # It's the unique id of each node. # unique id of this employee self.id = id # the importance value of this employee self.importance = importance # the id of direct subordinates self.subordinates = subordinates """ class Solution: def getImportance(self, employees, id): """ :type employees: Employee :type id: int :rtype: int """ self.res = 0 emp_infos = dict() for employee in employees: emp_infos[employee.id] = [employee.importance,employee.subordinates] def dfs(subs): for sub in subs: self.res += emp_infos[sub][0] dfs(emp_infos[sub][1]) dfs([id]) return self.res
2.图像渲染 leetcode 773
以中心点上下左右扩散
思路:深度搜索,遍历中心点的上下左右四个点,然后到达一个点,再继续遍历其到上下左右到节点,直到碰到边界,就返回
class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: self.recode = [] self.m = len(image) self.n = len(image[0]) def dfs(sr,sc,image): directions = [[-1,0],[1,0],[0,-1],[0,1]]#上下左右 for d in directions: new_sr = sr+d[0] new_sc = sc+d[1] if new_sr >= 0 and new_sr < self.m and new_sc >= 0 and new_sc < self.n:#未越界 if image[new_sr][new_sc] == image[sr][sc] and [new_sr,new_sc] not in self.recode: print(new_sr,new_sc) self.recode.append([new_sr,new_sc]) dfs(new_sr,new_sc,image) dfs(sr,sc,image) image[sr][sc] = newColor for src in self.recode: n_sr,n_sc = src[0],src[1] image[n_sr][n_sc] = newColor return image
3.岛屿的个数 leetcode200
思路:深度搜索
class Solution(object): dx = [1,0,-1,0] dy = [0,-1,0,1] def numIslands(self, grid): ans = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == '1': self.dfs(grid,i,j) ans +=1 return ans def dfs(self,grid,i,j): grid[i][j] = '.' for k in range(4): m = i+self.dx[k] n = j+self.dy[k] if m>-1 and m<len(grid) and n >-1 and n<len(grid[0]) and grid[m][n] == '1': self.dfs(grid,m,n) return
4.两点间路径条数
思路:深度遍历
# row, col = map(int, input().split()) # graph = [] # for _ in range(row): # graph.append(list(map(int, input().split()))) # print(graph) # x1, y1, x2, y2 = map(int, input().split()) dirs = [(-1, 0), (1, 0), (0, 1), (0, -1)]#上,下,右,左 M = 10 ** 9 res = [0] graph = [[0, 1, 0, 0, 0], [0, 2, 3, 0, 0], [0, 0, 4, 5, 0], [0, 0, 7, 6, 0]] row = 4 col = 5 x1, y1, x2, y2 = 0, 1, 3, 2 def dfs(x1, y1, visited): if x1 == x2 and y1 == y2: res[0] += 1 return for i, j in dirs:#遍历4个方向,判断下一步哪步可行,然后从这步开始,继续深度遍历,直到到达终点 tmp_x = i + x1 tmp_y = j + y1 if 0 <= tmp_x < row and 0 <= tmp_y < col and graph[tmp_x][tmp_y] > graph[x1][y1] \ and (tmp_x, tmp_y) not in visited: dfs(tmp_x, tmp_y, visited | {(tmp_x, tmp_y)}) print (visited) dfs(x1, y1, {(x1, y1)}) print(res[0] % M)