用棧消除遞歸調用,實現DFS【僞代碼】

DFS(G)it

  for each vertex u in G.Vim

  u.color = whitetop

  u.pi = NILwhile

  time = 0co

  let A be a stacktime

  for each vertex u in G.Vlet

    if u.color == whitepush

    A.push(u)

  while A is not empty

    x = A.top()

    flag = 0

    for each v in G:Adj[x]

      if v.color == white//遇到堆棧頂端元素相鄰的節點有白色的都入棧

        flag = 1

        time = time + 1

        v.d = time

        v.pi = x

        v.color = gray

        A.push(v)

    if flag == 0//若是棧頂端節點全部相鄰節點都不是白色【均被標記爲灰色或者黑色】則出棧

      y = A.pop()

      y.color = black

      time = time + 1

      y.f = time

相關文章
相關標籤/搜索