欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python數(shù)據(jù)結(jié)構(gòu)與算法之圖的廣度優(yōu)先與深度優(yōu)先搜索算法示例

 更新時(shí)間:2017年12月14日 11:56:53   作者:hanahimi  
這篇文章主要介紹了Python數(shù)據(jù)結(jié)構(gòu)與算法之圖的廣度優(yōu)先與深度優(yōu)先搜索算法,結(jié)合實(shí)例形式分析了圖的廣度優(yōu)先與深度優(yōu)先搜索算法原理與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了Python數(shù)據(jù)結(jié)構(gòu)與算法之圖的廣度優(yōu)先與深度優(yōu)先搜索算法。分享給大家供大家參考,具體如下:

根據(jù)維基百科的偽代碼實(shí)現(xiàn):

廣度優(yōu)先BFS:

使用隊(duì)列集合

標(biāo)記初始結(jié)點(diǎn)已被發(fā)現(xiàn),放入隊(duì)列

每次循環(huán)從隊(duì)列彈出一個(gè)結(jié)點(diǎn)

將該節(jié)點(diǎn)的所有相連結(jié)點(diǎn)放入隊(duì)列,并標(biāo)記已被發(fā)現(xiàn)

通過隊(duì)列,將迷宮路口所有的門打開,從一個(gè)門進(jìn)去繼續(xù)打開里面的門,然后返回前一個(gè)門處

"""
 procedure BFS(G,v) is
   let Q be a queue
   Q.enqueue(v)
   label v as discovered
   while Q is not empty
    v ← Q.dequeue()
    procedure(v)
    for all edges from v to w in G.adjacentEdges(v) do
      if w is not labeled as discovered
        Q.enqueue(w)
        label w as discovered
"""
def procedure(v):
  pass
def BFS(G,v0):
  """ 廣度優(yōu)先搜索 """
  q, s = [], set()
  q.extend(v0)
  s.add(v0)
  while q:  # 當(dāng)隊(duì)列q非空
    v = q.pop(0)
    procedure(v)
    for w in G[v]:   # 對(duì)圖G中頂點(diǎn)v的所有鄰近點(diǎn)w
      if w not in s: # 如果頂點(diǎn) w 沒被發(fā)現(xiàn)
        q.extend(w)
        s.add(w)  # 記錄w已被發(fā)現(xiàn)

深度優(yōu)先DFS

使用 ,集合

初始結(jié)點(diǎn)入棧

每輪循環(huán)從棧中彈出一個(gè)結(jié)點(diǎn),并標(biāo)記已被發(fā)現(xiàn)

對(duì)每個(gè)彈出的結(jié)點(diǎn),將其連接的所有結(jié)點(diǎn)放到隊(duì)列中

通過棧的結(jié)構(gòu),一步步深入挖掘

""""
Pseudocode[edit]
Input: A graph G and a vertex v of G
Output: All vertices reachable from v labeled as discovered
A recursive implementation of DFS:[5]
1 procedure DFS(G,v):
2   label v as discovered
3   for all edges from v to w in G.adjacentEdges(v) do
4     if vertex w is not labeled as discovered then
5       recursively call DFS(G,w)
A non-recursive implementation of DFS:[6]
1 procedure DFS-iterative(G,v):
2   let S be a stack
3   S.push(v)
4   while S is not empty
5      v = S.pop()
6      if v is not labeled as discovered:
7        label v as discovered
8        for all edges from v to w in G.adjacentEdges(v) do
9          S.push(w)
"""
def DFS(G,v0):
  S = []
  S.append(v0)
  label = set()
  while S:
    v = S.pop()
    if v not in label:
      label.add(v)
      procedure(v)
      for w in G[v]:
        S.append(w)

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論