class GraphAdjacencyMatrix:
def __init__(self, num_vertices):
self.num_vertices = num_vertices
self.matrix = [[0] * num_vertices for _ in range(num_vertices)]
def add_edge(self, start, end): # 无向图
self.matrix[start][end] = 1
self.matrix[end][start] = 1
2.邻接表:
python复制代码
from collections import defaultdict
class GraphAdjacencyList:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, start, end): # 无向图
self.graph[start].append(end)
self.graph[end].append(start)
3.图的遍历:
python复制代码
# 深度优先搜索(DFS):
# 从上到下,递归或栈实现
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=" ")
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
# 广度优先搜索(BFS):
# 从左到右,队列实现
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
current = queue.popleft()
print(current, end=" ")
for neighbor in graph[current]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
def dfs(nums, x, y):
if x<0 or x>len(nums)-1: return
if y<0 or y>len(nums[0])-1: return
if nums[x][y] =='0':return
else:
nums[x][y] = '0' # 必须先置0,否则会在两个'1'间连续递归至超过栈长
dfs(nums, x-1, y)
dfs(nums, x+1, y)
dfs(nums, x, y-1)
dfs(nums, x, y+1)
cnt = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
dfs(grid, i, j)
cnt += 1
return cnt
方法二:广度优先搜索 BFS
若当前点是岛屿时,将其上下左右四个点都加入队列;终止条件:越界;当前是水;
python复制代码
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
def bfs(nums, x, y):
queue = [(x, y)]
while queue:
(x, y) = queue.pop(0)
if x<0 or x>len(nums)-1: continue
elif y<0 or y>len(nums[0])-1: continue
elif nums[x][y] =='0':continue
else:
nums[x][y] = '0' # 必须先置0,否则会在两个'1'间连续递归至超过栈长
queue.append((x-1, y))
queue.append((x+1, y))
queue.append((x, y-1))
queue.append((x, y+1))
cnt = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
bfs(grid, i, j)
cnt += 1
return cnt
class Solution(object):
def orangesRotting(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
cnt, queue = 0, []
m, n = len(grid), len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
cnt += 1
elif grid[i][j] == 2:
queue.append([i,j])
if cnt == 0: return 0
time, stack = -1, []
while queue:
[x, y] = queue.pop(0)
if -1<x<m and -1<y<n and grid[x][y]:
if grid[x][y] == 1: cnt -= 1
grid[x][y] = 0 # 不再处理这个点
stack.append([x-1, y])
stack.append([x+1, y])
stack.append([x, y-1])
stack.append([x, y+1])
if not queue and stack:
queue = stack
time += 1
stack = []
return -1 if cnt else time