判斷有向圖是否有環及環中元素
阿新 • • 發佈:2019-01-21
主要思路: dfs+棧。具體來說,遍歷圖中每個節點,若該節點還未被訪問,則呼叫dfs。在訪問節點n時,若該節點不在棧中,則將其入棧,否則說明存在環,並且環中元素為棧中從節點n到棧頂的所有點。
# 輸入:第一行為圖中的邊數,餘下行為兩個節點組成的邊,以空格劃分
例:
8
1 2
2 3
3 1
3 4
5 4
5 6
6 7
7 5
程式碼:
import sys
def dfs(node, graph, visited, stack):
visited[node] = True
stack.append(node)
if node in graph:
for n in graph[node]:
if n not in stack:
if not visited[n]:
dfs(n, graph, visited, stack)
else:
index = stack.index(n)
print 'Circle: ',
for i in stack[index:]:
print i,
print n
stack.pop(-1)
def main():
graph = {}
visited = {}
stack = []
num = int(sys.stdin.readline())
for i in range(num):
n1, n2 = sys.stdin.readline().strip().split(' ')
if n1 not in graph:
graph[n1] = [n2]
elif n2 not in graph[n1]:
graph[n1].append(n2)
if n1 not in visited:
visited[n1] = False
if n2 not in visited:
visited[n2] = False
for node in visited.keys():
if not visited[node]:
dfs(node, graph, visited, stack)
if __name__ == "__main__":
main()
示例:
以下圖為例:
輸入及結果:
# 輸入
8
1 2
2 3
3 1
3 4
5 4
5 6
6 7
7 5
# 輸出
Circle: 1 2 3 1
Circle: 5 6 7 5