Exemplo n.º 1
0
def dijkstra(aGraph: Graph, start: Vertex):
    pq = PriorityQueue()
    start.setDistance(0)
    pq.buildHeap([(v.getDistance(), v) for v in aGraph])
    while not pq.isEmpty():
        currentVert = pq.delMin()
        for nextVert in currentVert.getConnections():
            newDist = currentVert.getDistance() + currentVert.getWeight(
                nextVert)
            if newDist < nextVert.getDistance():
                nextVert.setDistance(newDist)
                nextVert.setPred(currentVert)
                pq.decreaseKey(nextVert, newDist)
Exemplo n.º 2
0
 def dfsvisit(self, startVertex: Vertex):
     startVertex.setColor("gray")
     self.time += 1
     startVertex.setDiscovery(self.time)
     for nextVertex in startVertex.getConnections():
         if nextVertex.getColor() == "white":
             nextVertex.setPred(startVertex)
             self.dfsvisit(nextVertex)
     startVertex.setColor("black")
     self.time += 1
     startVertex.setFinish(self.time)
Exemplo n.º 3
0
def prim(G: Graph, start: Vertex):
    pq = PriorityQueue()
    for v in G:
        v.setDistance(sys.maxsize)
        v.setPred(None)
    start.setDistance(0)
    pq.buildHeap([(v.getDistance(), v) for v in G])
    while not pq.isEmpty():
        currentVert = pq.delMin()
        for nextVert in currentVert.getConnections():
            newCost = currentVert.getWeight(nextVert)
            if nextVert in pq and newCost < nextVert.getDistance():
                nextVert.setPred(currentVert)
                nextVert.setDistance(newCost + currentVert.getDistance())
                pq.decreaseKey(nextVert, newCost)
Exemplo n.º 4
0
def bfs(g: Graph, start: Vertex):
    start.setDistance(0)
    start.setPred(None)

    vertQueue = Queue()
    vertQueue.enqueue(start)

    while vertQueue.size() > 0:
        currentVert = vertQueue.dequeue()
        for nbr in currentVert.getConnections():
            if nbr.getColor() == 'white':
                nbr.setColor('gray')
                nbr.setDistance(currentVert.getDistance() + 1)
                nbr.setPred(currentVert)
                vertQueue.enqueue(nbr)
        currentVert.setColor('black')
Exemplo n.º 5
0
    def dfsVisit(self, startVertex: Vertex):
        startVertex.setColor('gray')
        self.time += 1
        startVertex.setDiscovery(self.time)

        for nextVertex in startVertex.getConnections():
            if nextVertex.getColor() == 'white':
                nextVertex.setPred(startVertex)
                self.dfsVisit(nextVertex)

        startVertex.setColor('black')
        self.time += 1
        startVertex.setFinish(self.time)
Exemplo n.º 6
0
def knightTour(n, path, u: Vertex, limit):
    u.setColor("gray")
    path.append(u)
    if n < limit:
        nbrList = list(u.getConnections())
        # nbrList = orderByAvail(u)
        i = 0
        done = False
        while i < len(nbrList) and not done:
            if nbrList[i].getColor() == "white":
                done = knightTour(n + 1, path, nbrList[i], limit)
            i = i + 1
        if not done:
            path.pop()
            u.setColor("white")
    else:
        done = True
    return done
Exemplo n.º 7
0
def main():
    start = bankCounts(
        3, 3, 1
    )  #The list contains the left bank counts for missionaries, cannibals, and the boat in that order
    goal = bankCounts(0, 0, 0)
    validTest = start.is_valid(3, 3, 1)
    print(validTest)
    vertex = Vertex(start)
    graph = buildGraph(counts)
    print(graph.getVertices)
    breadthFirstSearch = bfs(graph, vertex)
Exemplo n.º 8
0
def orderByAvail(n: Vertex):
    resList = []
    for v in n.getConnections():
        if v.getColor() == "white":
            c = 0
            for w in v.getConnections():
                if w.getColor() == "white":
                    c = c + 1
            resList.append((c, v))
    resList.sort(key=lambda x: x[0])
    return [y[1] for y in resList]
Exemplo n.º 9
0
def knightTour(n, path, u: Vertex, limit):
    u.setColor('gray')
    path.append(u)

    if n < limit:
        nbrList = list(u.getConnections())
        i = 0
        done = False
        while i < len(nbrList) and not done:
            if nbrList[i].getColor() == 'white':
                done = knightTour(n + 1, path, nbrList[i], limit)
            i += 1

        if not done:  # prepare to backtrack
            path.pop()
            u.setColor('white')
        else:
            done = True

        return done
Exemplo n.º 10
0
        def dfs(vertex: Vertex, i):
            vertex.color = 'gray'
            path.append(str(vertex.id))
            if i >= n:
                return True
            find = False
            for neighbor in get_neighbors(vertex, strategy=order_by_avail):
                if neighbor.color != 'white':
                    continue
                find = dfs(neighbor, i + 1)
                if find:
                    break
                path.pop()
                neighbor.color = 'white'

            return find
Exemplo n.º 11
0
def main(args):

    # TODO:  add proper TESTs to initialize Graph and Vertex with graph example from GeeksForGeeks!

    # print type(Graph)
    # print dir(Graph)

    # print type(Vertex)
    # print dir(Vertex)
    # help(Vertex.__init__)

    # print dir(PriorityQueue)

    vertex0 = Vertex(0)
    vertex0.setDistance(0)
    # print vertex0

    vertex1 = Vertex(1)
    # print vertex1

    vertex7 = Vertex(7)
    # print vertex7

    vertex2 = Vertex(2)
    # print vertex2

    graph1 = Graph()
    graph1.addVertex(vertex0)
    graph1.addVertex(vertex1)
    graph1.addVertex(vertex7)
    graph1.addVertex(vertex2)

    print 'Initialized Vertex Dump:'
    # for aVertex in graph1.getVertices():
    #     print aVertex

    print 'Initialized Edges Dump:'
    graph1.addEdge(vertex0, vertex1, 4)
    graph1.addEdge(vertex0, vertex7, 8)
    graph1.addEdge(vertex1, vertex2, 8)

    print 'Vertex Sequenced after Djikstra from starting point with key 0'
    try:
        dijkstra(graph1, vertex0)
        for aVertex in graph1.getVertices():
            print aVertex
    except Exception as ex:
        logging.exception("BURP!")
Exemplo n.º 12
0
 def add_vertex(self, key):
     self.vertexes[key] = Vertex(key)
Exemplo n.º 13
0
        currentVert = vertQueue.dequeue()
        # 遍历多有的边
        for nbr in currentVert.getConnections():
            if (nbr.getColor() == 'white'):
                nbr.setColor('gray')
                nbr.setDistance(currentVert.getDistance() + 1)
                nbr.setPred(currentVert)
                vertQueue.enqueue(nbr)

        currentVert.setColor('black')


wordFile = './DS7_Graph/word.txt'
g = buildGraph(wordFile).getVertices()

start = Vertex('FOOL')

print(bsf(g, start))


def traverse(e):
    x = e
    while (x.getPred()):
        print(x.getId())
        x.getPred()
    print(x.getId())


'''
    s:'FOOL'
    相邻点:pool,foil,foul,cool
Exemplo n.º 14
0
def bfs(g, start):
    # 设置距离为0,前导为None
    start.setDistance(0)
    start.setPred(None)
    vertQueue = Queue()
    vertQueue.enqueue(start)

    while (vertQueue.size() > 0):
        currentVert = vertQueue.dequeue()
        for nbr in currentVert.getConnections():
            if (nbr.getColor() == 'white'):
                nbr.setColor('gray')
                nbr.setDistance(currentVert.getDistance() + 1)
                nbr.setPred(currentVert)
                vertQueue.enqueue(nbr)
        currentVert.setColor('black')


start = Vertex(0)
print(bfs(g, start))


def traverse(y):
    x = y
    while (x.getPred()):
        print(x.getId())
        x = x.getPred()
    print(x.getId())


# print(g.getVertex('FOOL'))
 def add_vertex(self, node):
     self.num_vertices = self.num_vertices + 1
     new_vertex = Vertex(node)
     self.vert_dict[node] = new_vertex
     return new_vertex
Exemplo n.º 16
0
 def addVertex(self,key):
     self.numVertices = self.numVertices + 1
     newVertex = Vertex(key)
     self.vertList[key] = newVertex
     return newVertex
Exemplo n.º 17
0
 def addVertex(self, key):
     #increments the vertices counter, instaniates a new vertex object, adds that new vertex object to graph dictionary.
     self.numVertices = self.numVertices + 1
     newVertex = Vertex(key)
     self.vertList[key] = newVertex
     return newVertex