我一直在努力與此一段時間了。給定一組節點:廣度優先搜索/深度優先搜索還是定向圖?
nodes = { ('A','B'),
('B','C'),
('C','D'),
('C','E'),
('B','E'),
('C','F') }
什麼是實現最好的辦法如下:
A
|
B
_________|_________
| |
C E
_____|_____ |
| | | C
D E F ____|____
| |
D F
在那裏我可以看到:
the routes from A -> B:
A -> B
the routes from A -> C:
A -> B -> C
A -> B -> E -> C
the routes from A -> D:
A -> B -> C -> D
A -> B -> E -> C -> D
etc...
我這樣做的原因,是純粹是因爲我想了解如何。
我知道BFS找到最快的路線,(我想我可能會用在讓孩子功能類似的東西)
,但我不知道循環的最佳方式/遞歸地在圖上運行。我應該使用字典並使用鍵/ val或列表。或設置...
def make_graph(nodes):
d = dict()
for (x,y,*z) in nodes:
if x not in d: d[x] = set()
if y not in d: d[y] = set()
d[x].add(y)
d[y].add(x)
return d
我在這裏用* Z作爲元組實際上將包括一個浮動,但此刻我試圖讓事情變得簡單。
def display_graph(nodes):
for (key,val) in make_graph(nodes).items():
print(key, val)
# A {'B'}
# C {'B', 'E', 'D', 'F'}
# B {'A', 'C', 'E'}
# E {'C', 'B'}
# D {'C'}
# F {'C'}
的功能的GetChildren找出所有可能的端點爲節點根:
def getchildren(noderoot,graph):
previousnodes, nextnodes = set(), set()
currentnode = noderoot
while True:
previousnodes.add(currentnode)
nextnodes.update(graph[currentnode] - previousnodes)
try:
currentnode = nextnodes.pop()
except KeyError: break
return (noderoot, previousnodes - set(noderoot))
在這種情況下:
print(getchildren('A', make_graph(nodes)))
# ('A', {'C', 'B', 'E', 'D', 'F'})
可能的重複[如何將一系列父子關係轉換爲分層樹?](http://stackoverflow.com/questions/2915748/102441)。不同的語言,但同樣的問題 – Eric
爲什麼'E'不出現在'C'的左邊? – Eric
C,D,F各兩個?你確定你想要一棵樹,而不是有向圖嗎? –