Randomized contraction algorithm for the Min Cuts in a graph

768 Views Asked by At

I have tried to write an implementation of Karger's algorithm for solving the min cut problem. Here's my code

def randomVertices(g): 
    v1 = g.keys() [random.randint(0,len(g)-1)]
    v2 = g[v1] [random.randint(0,len(g[v1])-1)]
    return v1, v2


def mergeVertices(g):
    v1,v2 = randomVertices(g)

    g[v1].extend(g[v2])

    for x in g[v2]:
        l = g[x]
        for i in range(0,len(l)):
            if l[i] == v2: 
                l[i] = v1        

    while v1 in g[v1]:
        g[v1].remove(v1)

    del g[v2]

def minCut(g): 
    while len(g) > 2: 
        mergeVertices(g)
    return len(g[g.keys()[0]])

It's not commented but it should be pretty self-explanatory. 'g' is a dictionary whose keys are the vertices of the graph, each with values the vertices it is connected to. randomVertices gives me the edge that I want to contract, while mergeVertices updates the dictionary (and hence the graph) by deleting the second vertex, updating the values of the keys which were linked to this vertex, and getting rid of the self-loops. It looks okay to me but if I run it on any test graph I get a KeyError at the l = g[x] stage, and I can't understand why this is happening. Was hoping that some of you may be able to help me. Thanks.

EDIT: my code is actually fine, the error was in the way I loaded the file with the adjacent list. Cobarzan, thank you for pointing out that I'm not actually picking edges uniformly.

0

There are 0 best solutions below