简体   繁体   English

随机遍历有向图

[英]Traversing a directed graph randomly

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. 我有一个有向图,下面的程序遍历图形从随机起点到随机终点。我需要它做的是随机遍历图形x次,每次从前一次随机选择一个节点节点,但我不知道如何实现这一点。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM