I have a directed graph and the following program traverses the graph from a random start point to a random finish point.What I need it to do is to traverse randomly through the graph x amount of times, randomly selecting a node each time from the previous node but I am not sure how to achieve this. It doesn't matter if nodes are visited more than once.
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()
If I understood correctly what you're asking, the following code should do it (see comments inline):
import random
def find_path(graph, start, end, path, max_):
# Append to the path
path.append(start)
# If the end has been reached, or the length about to exceed, return
if start == end or len(path) == max_:
return path
# Randomly select the next neighbor and traverse it
find_path(graph, random.choice(graph[start]), end, path, max_)
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]}
start = random.randint(1, 10)
end = random.randint(1, 10)
path = []
find_path(graph, start, end, path, 20)
print start, end, path
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.