1. 程式人生 > >基於二維矩陣的深搜(dfs)和廣搜(bfs)python實現

基於二維矩陣的深搜(dfs)和廣搜(bfs)python實現

該二維矩陣不是鄰接矩陣,每個結點只和上下左右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