大厂面试高频题目——图论
797.所有可能的路径
给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
graph[i] 是一个从节点 i 可以访问的所有节点的列表(即从节点 i 到节点 graph[i][j]存在一条有向边)。

思考
深搜dfs模板题。
class Solution:
def __init__(self):
self.path = []
self.res = []
def dfs(self,graph,x):
if self.path[-1] == len(graph)-1:
self.res.append(self.path[:])
return
for i in graph[x]:
self.path.append(i)
self.dfs(graph,i)
self.path.pop()
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
self.path.append(0)
self.dfs(graph,0)
return self.res
200. 岛屿数量
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。

思考
按行列开始遍历,记录访问过的陆地节点,如果遇到新的没有访问过的陆地节点,岛屿计数器+1,同时基于这个陆地节点进行搜索(深搜或广搜都可以),把临近的陆地节点都标记成已访问。
- 深搜版本
class Solution:
def dfs(self,grid,visited,i,j):
dir = [[-1,0],[1,0],[0,-1],[0,1]]
m = len(grid)
n = len(grid[0])
for dx,dy in dir:
next_x,next_y = i+dx,j+dy
if next_x<0 or next_x > m-1 or next_y<0 or next_y > n-1:
continue
#print(m,n,next_x,next_y)
if grid[next_x][next_y] == '0' or visited[next_x][next_y]:
continue
visited[next_x][next_y] = True
self.dfs(grid,visited,next_x,next_y)
def numIslands(self, grid: List[List[str]]) -> int:
m = len(grid)
n = len(grid[0])
visited = [[False] * n for _ in range(m)]
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] =='1' and not visited[i][j]:
res+=1
visited[i][j] = True
self.dfs(grid,visited,i,j)
return res
2.bfs版本
class Solution:
def bfs(self,grid,visited,i,j):
dir = [[-1,0],[1,0],[0,-1],[0,1]]
m = len(grid)
n = len(grid[0])
queue = deque()
queue.append((i,j))
while queue:
i,j = queue.popleft()
for dx,dy in dir:
next_x,next_y = i+dx,j+dy
if next_x<0 or next_x > m-1 or next_y<0 or next_y > n-1:
continue
#print(m,n,next_x,next_y)
if grid[next_x][next_y] == '0' or visited[next_x][next_y]:
continue
visited[next_x][next_y] = True
queue.append((next_x,next_y))
def numIslands(self, grid: List[List[str]]) -> int:
m = len(grid)
n = len(grid[0])
visited = [[False] * n for _ in range(m)]
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] =='1' and not visited[i][j]:
res+=1
visited[i][j] = True
self.bfs(grid,visited,i,j)
return res
79. 单词搜索
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
path = []
m = len(board)
n = len(board[0])
visited = [[False] * n for _ in range(m)]
def dfs(i,j, k):
if board[i][j] != word[k]:
return False
if k == len(word) - 1:
return True
visited[i][j] = True
dir = [[-1,0],[1,0],[0,-1],[0,1]]
res = False
for dx,dy in dir:
next_x,next_y = i+dx,j+dy
if next_x<0 or next_x > m-1 or next_y<0 or next_y > n-1:
continue
if visited[next_x][next_y]:
continue
if dfs(next_x,next_y,k+1):
res = True
break
visited[i][j] = False
return res
for i in range(m):
for j in range(n):
if dfs(i,j,0):
return True
return False
浙公网安备 33010602011771号