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)
def bfs(visited,graph,node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print(s,end='->')
for neighbor in graph[s]:
if neighbor not in visited:
visited.append(neighbor)
queue.append(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()
# dfs
d = 0
for node in v:
visited=set()
d = 0
dfs(visited,g,node)
print(':',d)
print()
# bfs
for node in v:
queue = []
visited = []
bfs(visited,g,node)
print()
print()
# = = = = =
Output:
['0', '1']
['0', '2']
['0', '3']
['7', '0']
['1', '4']
['1', '5']
['3', '6']
0 {'3', '2', '7', '1'}
1 {'0', '5', '4'}
2 {'0'}
3 {'0', '6'}
4 {'1'}
5 {'1'}
6 {'3'}
7 {'0'}
0->3->6->2->7->1->5->4->: 8
1->0->3->6->2->7->5->4->: 8
2->0->3->6->7->1->5->4->: 8
3->0->2->7->1->5->4->6->: 8
4->1->0->3->6->2->7->5->: 8
5->1->0->3->6->2->7->4->: 8
6->3->0->2->7->1->5->4->: 8
7->0->3->6->2->1->5->4->: 8
0->3->2->7->1->6->5->4->
1->0->5->4->3->2->7->6->
2->0->3->7->1->6->5->4->
3->0->6->2->7->1->5->4->
4->1->0->5->3->2->7->6->
5->1->0->4->3->2->7->6->
6->3->0->2->7->1->5->4->
7->0->3->2->1->6->5->4->
>
沒有留言:
張貼留言