Exemple #1
0
def knightsGraph(board_size=8):
    g = Graph()
    for row in range(board_size):
        for col in range(board_size):
            currPos = getNormalizedPos(row, col, board_size)
            newPos = getPossiblePositions(row, col, board_size)
            for pos in newPos:
                g.addEdge(currPos, pos)
    return g
Exemple #2
0
def allMoves(bdSize):
    ktGraph = Graph()
    for row in range(bdSize):
        for col in range(bdSize):
            nodeId = posToNodeId(row, col, bdSize)
            newPositions = genAllMoves(row, col, bdSize)
            for e in newPositions:
                nid = posToNodeId(e[0], e[1], bdSize)
                ktGraph.addEdge(nodeId, nid)
    return ktGraph
Exemple #3
0
def knightGraph(bdSize):
    ktGraph = Graph()
    for row in range(bdSize):
        for col in range(bdSize):
            #import pdb; pdb.set_trace()
            nodeId = posToNodeId(row, col, bdSize)
            newPositions = genLegalMoves(row, col, bdSize)
            for e in newPositions:
                nid = posToNodeId(e[0], e[1], bdSize)
                ktGraph.addEdge(nodeId, nid)
    #            import pdb; pdb.set_trace()
    return ktGraph
def buildGraph(words):
    d = {}
    g = Graph()
    for word in words:
        for i in range(len(word)):
            bucket = word[:i] + "_" + word[i + 1:]
            if bucket in d:
                d[bucket].append(word)
            else:
                d[bucket] = [word]
    for bucket in d.keys():
        for word1 in d[bucket]:
            for word2 in d[bucket]:
                if word1 != word2:
                    g.addEdge(word1, word2)
    return g
def prims(graph, start):
    print("Finding minimum spanning tree")
    graph.print()

    minSpanTree = Graph()
    heap = EdgeMinHeap()
    visited = dict()
    for vertex in graph.getVertices():
        visited[vertex] = False

    minSpanTree.addVertex(start)
    visited[start] = True

    print("Adding edges adjacent to initial vertex to potential edges")
    for edge in graph.getAdjEdges(start):
        heap.siftUp(edge[0], edge[1], edge[2])
    heap.print()

    done = heap.isEmpty()
    while not done:
        print("Sifting down to find shortest edge with an unvisited destination")
        heap.print()
        top = heap.siftDown()
        found = not visited[top[1]] # top.to
        done = heap.isEmpty()
        heap.print()
        while not found and not done:
            top = heap.siftDown()
            found = not visited[top[1]]
            heap.print()
            if heap.isEmpty():
                done = True

        if not found:
            break
        print(str(top) + " is a valid edge. Adding to MST")
        visited[top[1]] = True
        minSpanTree.addVertex(top[1])
        minSpanTree.addEdge(top[0], top[1], top[2])
        print("Adding edges adjacent to " + str(top[1]) + " to potential edges")
        for edge in graph.getAdjEdges(top[1]):
            if not visited[edge[1]]:
                heap.siftUp(edge[0], edge[1], edge[2])
        heap.print()

    return minSpanTree
Exemple #6
0
def create_word_puzzle_graph(fl):
    d = {}
    with open(fl, 'r') as f:
        for word in f:
            word = word[:-1]
            for i in range(len(word)):
                bucket = word[:i] + '_' + word[i+1:]
                if d.has_key(bucket):
                    d[bucket].append(word)
                else:
                    d[bucket] = [word]
    g = Graph()
    for start in d.keys():
        wordlist = d[start]
        if len(wordlist) <= 1:
            continue
        for word in wordlist[1:]:
            g.addEdge(wordlist[0], word)
    return g
def buildGraph(wordFile):
    d = {}
    g = Graph()
    with open(wordFile) as wfile:
        for line in wfile:
            word = line.strip()
            for i in range(len(word)):
                bucket = word[:i] + '_' + word[i + 1:]
                if d.get(bucket, False):
                    d[bucket].append(word)
                else:
                    d[bucket] = []
                    d[bucket].append(word)

    #return d

    for bucket in d.keys():
        for word1 in d[bucket]:
            for word2 in d[bucket]:
                if word1 != word2:
                    g.addEdge(word1, word2)
    return g
Exemple #8
0
def buildGraph(wordFile):
    d = {}
    g = Graph()
    wfile = open(wordFile, 'r')
    # create buckets of words that differ by one letter
    for line in wfile:
        word = line[:-1]
        for i in range(len(word)):

            bucket = word[:i] + '_' + word[i + 1:]
            if bucket in d:
                d[bucket].append(word)
            else:
                d[bucket] = [word]
    # add vertices and edges for words in the same bucket
    for bucket in d.keys():
        for word1 in d[bucket]:
            for word2 in d[bucket]:
                if word1 != word2:
                    g.addEdge(word1, word2)

    return g
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 31 23:35:38 2016

@author: jpdjere
"""

from graphs import Node, Edge, Digraph, Graph

nodes = []
nodes.append(Node("ABC"))  # nodes[0]
nodes.append(Node("ACB"))  # nodes[1]
nodes.append(Node("BAC"))  # nodes[2]
nodes.append(Node("BCA"))  # nodes[3]
nodes.append(Node("CAB"))  # nodes[4]
nodes.append(Node("CBA"))  # nodes[5]

g = Graph()
for n in nodes:
    g.addNode(n)

g.addEdge(Edge(g.getNode('ABC'), g.getNode('ACB')))
g.addEdge(Edge(g.getNode('ACB'), g.getNode('CAB')))
g.addEdge(Edge(g.getNode('CAB'), g.getNode('CBA')))
g.addEdge(Edge(g.getNode('CBA'), g.getNode('BCA')))
g.addEdge(Edge(g.getNode('BCA'), g.getNode('BAC')))
g.addEdge(Edge(g.getNode('BAC'), g.getNode('ABC')))

print(g)
    n = g.getSize()
    leaves = []
    for node in g:
        vertex = g.getVertex(node)
        if vertex.degree == 0 or vertex.degree == 1:
            leaves.append(vertex)
            vertex.setDegree(0)
    count = len(leaves)
    while count < n:
        new_leaves = []
        for node in leaves:
            for nbr in node.getConnections():
                vertex = g.getVertex(nbr)
                vertex.setDegree(vertex.getDegree() - 1)
                if vertex.getDegree() == 1:
                    new_leaves.append(vertex)
            node.setDegree(0)
        count += len(new_leaves)
        leaves = new_leaves
    return leaves


for t in range(int(input())):
    n = int(input())
    g = Graph()
    for i in range(n):
        a, b = map(str, input().split())
        g.addEdge(a, b)

    print(treeCenters(g))
Exemple #11
0
from graphs import Vertex, Graph

wordlist='wordlist.txt'
file=open(wordlist,'r')

words={}
g = Graph()

# create word buckets and add words associated with each bucket
for line in file:
    word = line[:-1]
    for i in range(len(word)):
        wordbucket=word[:i]+'_'+word[i:]

        # if word doesnt exist in words dict add it to the list for that bucket
        if wordbucket in words:
            words[wordbucket].append(word)
        # add first word bucket to dictionary
        else:
            words[wordbucket]=[word]

 # Connect all the words within each work bucket together   
for wordbucket in words.keys():
    for word1 in words[wordbucket]:
        for word2 in words[wordbucket]:
            g.addEdge(word1,word2,0)



Exemple #12
0
    def dfs(g, ordering, v):
        for node in v.getConnections():
            vertex = g.getVertex(node)
            if vertex.isVisited():
                continue
            dfs(g, ordering, vertex)
        v.setVisited(True)
        ordering.appendleft(v.val)

    def helper(g, ordering):
        for node in g:
            vertex = g.getVertex(node)
            if vertex.isVisited():
                continue
            dfs(g, ordering, vertex)

    ordering = deque()
    helper(g, ordering)
    return ordering


if __name__ == '__main__':
    for t in range(int(input())):
        n = int(input())
        g = Graph(undirected=False)
        for i in range(n):
            src, dst = map(int, input().split())
            g.addEdge(src, dst)
        order = topological_sorting(g)
        print(order)