1

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()
user2987377
  • 91
  • 2
  • 9

1 Answers1

1

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
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185