Exemplo n.º 1
0
class OEIS:

    def __init__(self, edges, title):
        self.id2name = dict()
        self.readTitle(title)
        self.graph = Digraph(len(self.id2name))
        self.readEdge(edges)
        #sanity check
        print "# of vertices ", self.graph.numOfVertices()
        print "# of edges ", self.graph.numOfEdges()

    def readTitle(self, title):
        f = open(title, 'r')
        lines = f.readlines()
        for line in lines:
            tokens = line.split(' ', 1)
            id = int(tokens[0]) - 1
            definition = tokens[1]
            self.id2name[id] = definition

    def readEdge(self, edges):
        f = open(edges, 'r')
        lines = f.readlines()
        total = 0
        for line in lines:
            tokens = line.split()
            start = int(tokens[0]) - 1
            count = int(tokens[1])
            if count != len(tokens) - 2:
                raise Exception("not match")
            total += count
            if count == 0: continue
            for end in tokens[2:]:
                end = int(end) - 1
                if end >= len(self.id2name): continue
                self.graph.addEdge(start, end)

    def getTitle(self, v):
        return self.id2name[v]
Exemplo n.º 2
0
    def pathTo(self, v):
        if not self.hasPathTo(v):
            return None
        path = []
        x = v
        while self.distTo[x] != 0:
            path.append(x)
            x = self.edgeTo[x]
        path.append(x)
        path.reverse()
        return path

if __name__ == "__main__":
    graph = Digraph(5)
    graph.addEdge(0, 1)
    graph.addEdge(1, 2)
    graph.addEdge(2, 3)
    source = 1
    bfs = BFS(graph, source)
    for i in range(graph.numOfVertices()):
        if bfs.hasPathTo(i):
            print "%d to %d (%d)" % (source, i, bfs.distanceTo(i))
            for x in bfs.pathTo(i):
                if x == source: print x,
                else: print "-> " + str(x),
            print "\n"
        else:
            print "%d to %d (-) : not connected\n" % (source, i)

Exemplo n.º 3
0
    def pathTo(self, v):
        if not self.hasPathTo(v):
            return None
        path = []
        x = v
        while self.distTo[x] != 0:
            path.append(x)
            x = self.edgeTo[x]
        path.append(x)
        path.reverse()
        return path


if __name__ == "__main__":
    graph = Digraph(5)
    graph.addEdge(0, 1)
    graph.addEdge(1, 2)
    graph.addEdge(2, 3)
    source = 1
    bfs = BFS(graph, source)
    for i in range(graph.numOfVertices()):
        if bfs.hasPathTo(i):
            print "%d to %d (%d)" % (source, i, bfs.distanceTo(i))
            for x in bfs.pathTo(i):
                if x == source: print x,
                else: print "-> " + str(x),
            print "\n"
        else:
            print "%d to %d (-) : not connected\n" % (source, i)