Random Walk on Graph with Specified Start Node and Steps

  • Share this:

Code introduction


This function performs a random walk on a given graph starting from a specified node and returns the path of the walk. The function initializes a visited set and the current node, and then walks for the specified number of steps, randomly choosing an unvisited neighbor node as the next step at each step.


Technology Stack : Graph-tool library, used for graph data structures and algorithms

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_walk(graph, start_node, steps):
    """
    Perform a random walk on a graph starting from a given node and walk a specified number of steps.

    :param graph: A graph-tool graph object
    :param start_node: The starting node for the walk
    :param steps: The number of steps to take in the walk
    :return: A list of nodes visited during the walk
    """
    visited = set()
    current_node = start_node
    visited.add(current_node)
    path = [current_node]

    for _ in range(steps):
        neighbors = graph.get_neighbors(current_node)
        if not neighbors:
            break
        next_node = neighbors[int(len(neighbors) * random.random())]
        if next_node not in visited:
            visited.add(next_node)
            current_node = next_node
            path.append(current_node)

    return path