for w,v in vLst:
            indegree[v] = indegree[v]+1
    sortedVertices = []
    #add all vertices with indegree 0 to the stack
    stack = [i for i in range(N) if indegree[i]==0]
    while stack:
        u = stack.pop()
        sortedVertices.append(u)
        for w,v in g.adjLst[u]:
            indegree[v] = indegree[v]-1
            LPT[v] = max(LPT[v], LPT[u]+w)
            if indegree[v] == 0:
                stack.append(v)
    if len(sortedVertices) == N:
        return sortedVertices, LPT
    print 'Contains Cycle'
    return False

N = 6
g = weightedGraph(N)
g.addEdge(0,2,3)
g.addEdge(0,1,5)
g.addEdge(1,3,6)
g.addEdge(2,3,7)
g.addEdge(2,5,2)
g.addEdge(3,4,-1)
g.addEdge(3,5,1)
g.addEdge(2,4,4)
g.addEdge(4,5,-2)
print topologicalSort(g)
예제 #2
0
from graph import weightedGraph
import heapq
def djikstra(a,S):
    N = len(a.adjLst)
    Visited = [False for i in xrange(N)]
    Distance = [float('inf') for i in xrange(N)]
    Distance[S] = 0
    heap = []
    heapq.heappush(heap,(0,S))
    for i in xrange(N):
        if heap:
            while(True):
                _,u = heapq.heappop(heap)
                if not Visited[u]:
                    break
            Visited[u] = True
            for weight_uv,v in a.adjLst[u]:
                if not Visited[v]:
                    if Distance[v] > Distance[u] + weight_uv:
                        Distance[v] = Distance[u] + weight_uv
                        heapq.heappush(heap, (Distance[v],v))
    print Distance
    return Distance
    
g = weightedGraph(4)
g.addEdge(0,1,1)
g.addEdge(1,2,2)
g.addEdge(2,3,3)
g.addEdge(3,0,4)
djikstra(g,0)