pythongraphminimum-spanning-tree

Remove all symmetrical relations in an adjacency list based on a minimum spanning tree set


So say I have an undirected, weighted graph represented using an adjacency list:

# Dict with key being source and value being list of connections made up of tuple of destination and cost
adjacency_list: dict[int, set[tuple[int, int]]] = {
    1: {(2, 5), (3, 11), (4, 7)},
    2: {(1, 5), (3, 1)},
    3: {(1, 11), (2, 1), (4, 11)},
    4: {(1, 7), (3, 11)},
}

Then an mst set to store the minimum spanning tree:

# Set made up of tuples of source, destination and cost
mst: set[tuple[int, int, int]] = {
    (1, 2, 5),
    (1, 4, 7),
    (2, 3, 1),
}

Is there a way I can remove all symmetrical and equal connections in the mst compared to the adjacency list. For example, remove the connection from 1 to 2 and the one from 2 to 1 in the adjacency list since the connection exists in the mst?

An image of the graph


Solution

  • I think first you would need to decide which connection you want to delete.

    I guess it's the 2 to 1, leaving only 1 to 2 left.

    Then iterate over your mst set.

    Find symetry.

    Delete it.

    
    for tree_path in mst:
        to_delete = tree_path[1]
        dest, weight = tree_path[0], tree_path[2]
    
        for al_tree_path in adjacency_list[to_delete]:
            # we've found symetry in adjacency list for a given node
            if al_tree_path == (dest, weight):
                adjacency_list[to_delete].remove(al_tree_path)
    
    
    

    That should leave you without symetry in adjacency_list given what was in the mst set.

    output for the case you've specified

    here's the way to store it as a set of tuples

    
    result = set()
    for key, value in adjacency_list.items():
        for tree_path in adjacency_list[key]:
            result.add((key, *tree_path))