该二维矩阵不是邻接矩阵,每个结点只和上下左右4个方向的结点有连接。
def bfs(start, matrix):
"""广搜"""
n = len(matrix)
queue = []
queue.append(start)
vis = [[False for _ in range(n)] for _ in range(n)]
vis[start[0]][start[1]] = True
dires = [[0, 1], [0, -1], [1, 0], [-1, 0]]
while queue:
x, y = queue.pop(0)
print(matrix[x][y], end=' ')
for dx, dy in dires:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < n and not vis[nx][ny]:
queue.append([nx, ny])
vis[nx][ny] = True
def dfs(start, matrix, vis):
"""深搜"""
dires = [[0, 1], [0, -1], [1, 0], [-1, 0]]
x, y = start[0], start[1]
print(matrix[x][y], end=' ')
vis[x][y] = True
for dx, dy in dires:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < n and not vis[nx][ny]:
dfs([nx, ny], matrix, vis)
n = 6
matrix = [
[3, 0, 5, 4, 1, 2],
[0, 4, 1, 3, 2, 5],
[3, 1, 5, 2, 4, 0],
[4, 3, 0, 2, 1, 5],
[3, 4, 2, 0, 1, 5],
[1, 5, 3, 4, 2, 0],
]
print('深搜dfs')
dfs([0, 0], matrix, [[False for _ in range(n)] for _ in range(n)])
print('\n广搜bfs')
bfs([0, 0], matrix)
# 运行结果
# 深搜dfs
# 3 0 5 4 1 2 5 2 3 1 4 0 3 1 5 2 4 0 5 1 2 0 3 4 3 4 2 0 1 5 0 2 4 3 5 1
# 广搜bfs
# 3 0 0 5 4 3 4 1 1 4 1 3 5 3 3 2 2 2 0 4 1 5 4 2 2 5 0 1 0 3 5 1 4 5 2 0