コード例 #1
0
def createRandomGraph(v,e):
    randAdjList = [] # Keep track of edges alredy called. Should ultimately contain unique set of e edges
    i = 0

    # Add check for if num edges are possible    
    max_possible_e = (v*(v-1))/2  
    if(e>max_possible_e):
        raise Exception("Error! Number of edges cannot exceed %d for %d edges" % (max_possible_e,v))
    
    while(i<e):
        # Generate a random pair of node ids (can't pick the same node twice)
        randNodePair = np.random.choice(range(1,v+1), 2, replace=False).tolist()
        randNodePairRev =  list(randNodePair)
        randNodePairRev.reverse()
        
        # Since undirected graph, check that neither a->b nor b->a has been picked
        if randNodePair not in randAdjList and randNodePairRev not in randAdjList:
            randAdjList.append(randNodePair)
            i+=1
    
    # Create random graph using randAdjList created above    
    rGraph = Graph()
    for i in range(1,v):
        rGraph.addNode(i)
    rGraph.createGraph(randAdjList)
    return rGraph
コード例 #2
0
def MST(graph, format="adjacency list"):
    parent = {}
    
    # Add all nodes in graph to list of unvisited nodes
    unvisited = graph.getNodeList()
    # Maintain weight dictionary. Initialize all node weights to infinity
    weight_dict = dict({id, float("inf")} for id in graph.getNodeList())
    
    # Initialize all nodes to not visited
    for node in graph.getNodeList():
        graph.getNodes()[node].visited = False

    # Pick a random node as start node
    startNode = int(np.random.choice(list(weight_dict.keys()), 1))
    weight_dict[startNode] = 0 # Set weight of start node to 0
    parent[startNode] = None # Start node has no parent node

    g_nodes = graph.getNodes()        
        
    while(len(unvisited) != 0): 
        curr = getMinEdge(weight_dict, unvisited)
        g_nodes[curr].visited = True
        unvisited.remove(curr)
               
        for edge in graph.getEdges(curr):  
            if g_nodes[edge].visited == False:
                if weight_dict[curr] + getWeight(graph, curr, edge) < weight_dict[edge]:
                    weight_dict[edge] = weight_dict[curr] + getWeight(graph, curr, edge)
                    parent[edge] = curr
                    
    # Store edges of MST in adjacency list format
    # Useful format for creating a graph out of it in the future
    adjList_MST = [[parent[key], key] for key in parent if parent[key] != None]
    
    # Choose return format
    # Either graph or adjacency list
    if format=="graph":
        MinSpanTree = Graph()
        MinSpanTree.createGraph(adjList_MST)
        g_nodes = graph.getNodes()
        for node in MinSpanTree.getNodes().values():
            node.location = g_nodes[node.nodeid].location
    else:
        MinSpanTree = adjList_MST
        
    return MinSpanTree