我有一個有向圖,下面的程序遍歷從一個隨機起點到一個隨機終點的圖。我需要做的是隨機遍歷圖x次數,每次從前一個節點隨機選擇一個節點,但我不知道如何實現這一點。節點訪問不止一次並不重要。隨機遍歷有向圖
def find_path(graph, start, end, path=[]):
path = path + [start]
print path
if start == end:
return path
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
print path
# main function
def main():
start = str(random.randint(1,10))
finish = str(random.randint(1,10))
print start
print finish
graph = {'1': ['9'],
'2': ['10'],
'3': ['6', '8'],
'4': ['1', '6'],
'5': ['1'],
'6': ['7'],
'7': ['1', '3'],
'8': ['2'],
'9': ['4'],
'10': ['3', '5']}
find_path(graph, start, finish)
if __name__ == '__main__':
main()
爲什麼你需要方法只是爲了獲得一個隨機數? –
也要小心你的可變默認參數。 http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument –