主要思路: 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