visited[u] = True
    stack.append((u,None))
    while stack:
        #print stack
        x,parent = stack.pop()
        i = 0
        for vertex in g.adjLst[x]:
            #print 'visiting',vertex,'from',x
            if not visited[vertex]:
                visited[vertex] = True
                #print 'setting',vertex,'as visited'
                stack.append((vertex,x))
                i = i+1
            else:   #trying to reach a vertex that has already been visited
                if vertex != parent: #if this vertex is something else than the parent vertex
                    return True
    #print visited
    return False
    
    
N = 6
g = unDGraph(N)
g.addEdge(0,5)
g.addEdge(0,1)
g.addEdge(1,2)
g.addEdge(2,3)
g.addEdge(3,4)
g.addEdge(4,1)
#print g.adjLst
print detectCycleUnDgraph(g)
Ejemplo n.º 2
0
    color = [-1 for i in xrange(N)]
    color[0] = 0
    
    availableClrs = [True for i in xrange(N)]
    for u in xrange(1,N):
        for v in g.adjLst[u]:
            #Process all adjacent vertices and flag their colors as unavailable
            if color[v] != -1:
                availableClrs[color[v]] = False
        cr = availableClrs.index(True)
        color[u] = cr
        availableClrs = [True for i in range(N)]
    for u in xrange(N):
        print u,color[u]

g1 = unDGraph(5)
g1.addEdge(0, 1)
g1.addEdge(0, 2)
g1.addEdge(1, 2)
g1.addEdge(1, 3)
g1.addEdge(2, 3)
g1.addEdge(3, 4)

greedyColoring(g1)

g2 = unDGraph(5)

g2.addEdge(0, 1)
g2.addEdge(0, 2)
g2.addEdge(1, 2)
g2.addEdge(1, 4)