def dfs(visited,graph,node):
if node not in visited:
global d
d+=1
print(node,end='->')
visited.add(node)
for neighbor in graph[node]:
dfs(visited,graph,neighbor)
a = '''8
0 1
0 2
0 3
7 0
1 4
1 5
3 6'''
# create graph
a = a.split('\n')
a.pop(0)
v =set()
e = []
for i in a:
t = i.split(' ')
print(t)
e.append(t)
for j in t:
v.add(j)
print()
v = list(v)
v.sort()
g ={}
for i in v:
t =set()
for j in e:
if i in j:
for k in j:
if k!= i:
t.add(k)
g[i] = t
for x,y in g.items():
print(x,y)
print()
# each node process
d = 0
for node in v:
visited=set()
d = 0
dfs(visited,g,node)
print(':',d)
# ====
Output:
['0', '1']
['0', '2']
['0', '3']
['7', '0']
['1', '4']
['1', '5']
['3', '6']
0 {'1', '3', '7', '2'}
1 {'5', '4', '0'}
2 {'0'}
3 {'0', '6'}
4 {'1'}
5 {'1'}
6 {'3'}
7 {'0'}
0->1->5->4->3->6->7->2->: 8
1->5->4->0->3->6->7->2->: 8
2->0->1->5->4->3->6->7->: 8
3->0->1->5->4->7->2->6->: 8
4->1->5->0->3->6->7->2->: 8
5->1->4->0->3->6->7->2->: 8
6->3->0->1->5->4->7->2->: 8
7->0->1->5->4->3->6->2->: 8
>
沒有留言:
張貼留言