1. 程式人生 > >圖的基本演算法--深度優先搜尋(dfs) 和 廣度優先搜尋(bfs)

圖的基本演算法--深度優先搜尋(dfs) 和 廣度優先搜尋(bfs)

#   圖
#           0
#         / | \
#        1  2 - 4
#       /
#      3

m = 999999    # 代表沒有連線
a = [[0, 1, 1, m, 1],    # 鄰接矩陣表示圖
     [1, 0, m, 1, m],
     [1, m, 0, m, 1],
     [m, 1, m, 0, m],
     [1, m, 1, m, 0]]

n = 5            # 總點數
sm = 0           # 訪問點計算
book = [0] * n   # 記錄已經訪問過的點

def dfs(cur)
:
""" :param cur: 當前訪問點 :return: """ global sm print('%d' % cur, end=' ') sm = sm + 1 if sm == n: return for i in range(0, n): if a[cur][i] == 1 and book[i] == 0: book[i] = 1 dfs(i) def dfs_non_recursion(cur): """ :param cur: 當前訪問點 :return: """
s = [] s.append(cur) # 棧 book[cur] = 1 while len(s) != 0: cur = s.pop() print('%d' % cur, end=' ') for i in range(n-1, -1, -1): # 為了個遞迴的列印順序相同 if a[cur][i] == 1 and book[i] == 0: book[i] = 1 s.append(i) def bfs
(cur):
""" :param cur: 當前訪問點 :return: """ q = [] # 佇列 q.append(cur) while len(q) != 0: cur = q.pop(0) print('%d' % cur, end=' ') for i in range(0, n): if a[cur][i] == 1 and book[i] == 0: book[i] = 1 q.append(i) if __name__ == "__main__": book[0] = 1 dfs(0) for i in range(n): book[i] = 0 print() dfs_non_recursion(0) for i in range(n): book[i] = 0 print() book[0] = 1 bfs(0)