Ejemplo n.º 1
0
    def test_find_love(self):
        '''
        Función encargada de probar la función find love.
        :return:
        '''
        # Primer test
        start, goal = 0, 4
        arcs = [(0, 1), (0, 2), (0, 3), (3, 4)]

        g = Graph(goal + 1)
        for arc in arcs:
            g.add_edge(arc[0], arc[1])
        self.assertEqual(g.find_love(start, goal), (2, ['3', '4']))

        # Segundo test
        start, goal = 0, 9
        arcs = [(0, 1), (0, 2), (0, 3), (1, 5), (2, 4), (3, 7), (4, 9), (5, 6),
                (7, 8), (6, 9), (8, 9)]

        g = Graph(goal + 1)
        for arc in arcs:
            g.add_edge(arc[0], arc[1])
        self.assertEqual(g.find_love(start, goal), (3, ['2', '4', '9']))

        # Tercer test
        start, goal = 0, 4
        arcs = [(0, 1), (0, 2), (0, 3), (1, 3), (2, 3), (2, 4)]

        g = Graph(goal + 1)
        for arc in arcs:
            g.add_edge(arc[0], arc[1])
        self.assertEqual(g.find_love(start, goal), (2, ['2', '4']))
Ejemplo n.º 2
0
    def start_graph(self):
        self.g_instance = Graph(self.goal + 1)

        # Agregamos los arcos al grafo
        for pair in self.arcs:
            self.g_instance.add_edge(pair[0], pair[1])

        # Buscamos la cantidad de personas necesarias para llegar de 'start' a 'goal'
        self.data = self.g_instance.find_love(self.start, self.goal)
def main():
    #print(np.full([5, 5], None))

    print("Prim's Algorithm")
    g = Graph(5)
    g.create_graph_with_edges(7)
    #g.create_graph_with_edges()
    g.make_adjacency_matrix()
    print(g.temp_array)
    g.temp_array[:, 3] = None  # Change All Values of a Certain Columnn
    print(g.temp_array)
Ejemplo n.º 4
0
def build_graph(rows: int = 4, cols:int = 4) -> Graph[T]:
    graph: Graph[T] = Graph()
    for i in range(0, rows):
        for j in range(0, cols):
            # print("{}{}".format(i, j), end=' ')
            v1_data: T = '{},{}'.format(i, j)
            adjacent_vertices: List[Tuple[int, int]] = get_edges(i, j, rows, cols)
            for adj_ver in adjacent_vertices:
                v2_data: T = '{},{}'.format(*adj_ver)
                graph.add_edge(v1_data, v2_data, reverse=False)
        # print()
    # print(get_edges(0, 0, rows, cols))
    return graph
Ejemplo n.º 5
0
def timetable(e1, e2, filename):
    """
    Description: Course timetable
    """
    start_time = time.time()

    g = Graph(e1, e2)
    g.select(0)
    g.select(1)
    g.make_regular()
    g.edges_color()
    g.info(filename)

    f = open(filename, 'a')
    f.write('\nExecuted time: ' + str(time.time() - start_time))
    f.close()

    return len(g.matching)
Ejemplo n.º 6
0
    if count != len(all_data_vertex_mapping):
        print("Graph has cycle.")
        return False, []

    return True, top_order


if __name__ == '__main__':

    #     H <-- E --------> F --> G
    #           ^           ^
    #           |           |
    #     A --> C <-- B --> D

    graph1 = Graph()
    graph1.add_edge('A', 'C', is_directed=True)
    graph1.add_edge('B', 'C', is_directed=True)
    graph1.add_edge('B', 'D', is_directed=True)
    graph1.add_edge('C', 'E', is_directed=True)
    graph1.add_edge('D', 'F', is_directed=True)
    graph1.add_edge('E', 'F', is_directed=True)
    graph1.add_edge('E', 'H', is_directed=True)
    graph1.add_edge('F', 'G', is_directed=True)

    # A: A-->C
    # B: B-->C, B-->D
    # C: C-->E
    # D: D-->F
    # E: E-->H, E-->F
    # F: F-->G
Ejemplo n.º 7
0
def num_edges(g):
    # For undirected graph, just sum up the size of
    # all the adjacency lists for each vertex
    sum_ = 0
    for i in range(g.vertices):
        temp = g.array[i].head_node
        while temp is not None:
            sum_ += 1
            temp = temp.next_element

    # Half the total sum as it is an undirected graph
    return sum_ // 2


g = Graph(9)
g.add_edge(0, 2)
g.add_edge(0, 5)
g.add_edge(2, 3)
g.add_edge(2, 4)
g.add_edge(5, 3)
g.add_edge(5, 6)
g.add_edge(3, 6)
g.add_edge(6, 7)
g.add_edge(6, 8)
g.add_edge(6, 4)
g.add_edge(7, 8)

g.add_edge(2, 0)
g.add_edge(5, 0)
g.add_edge(3, 2)
Ejemplo n.º 8
0
# References:
# https://www.geeksforgeeks.org/kruskals-algorithm-simple-implementation-for-adjacency-matrix/?ref=rp

if __name__ == '__main__':
    #
    #       1     6
    #   A ---- D ---- E
    #   |     /|     /|
    # 3 |  3/  |1  /5 | 2
    #   | /    | /    |
    #   B ---- C ---- F
    #      1      4
    #

    graph: Graph[T] = Graph()
    graph.add_edge('A', 'B', weight=3, reverse=False)
    graph.add_edge('A', 'D', weight=1, reverse=False)
    graph.add_edge('B', 'C', weight=1, reverse=False)
    graph.add_edge('B', 'D', weight=3, reverse=False)
    graph.add_edge('C', 'D', weight=1, reverse=False)
    graph.add_edge('C', 'E', weight=5, reverse=False)
    graph.add_edge('C', 'F', weight=4, reverse=False)
    graph.add_edge('D', 'E', weight=6, reverse=False)
    graph.add_edge('E', 'F', weight=2, reverse=False)

    print("Adjacency list:")
    # A: A--(3)-->B, A--(1)-->D
    # B: B--(3)-->D, B--(1)-->C
    # C: C--(1)-->D, C--(4)-->F, C--(5)-->E
    # D: D--(6)-->E
Ejemplo n.º 9
0

# TODO
# https://www.geeksforgeeks.org/detect-cycle-in-an-undirected-graph-using-bfs/
def detect_cycle_using_BFS(graph: Graph[T]) -> Tuple[bool, List[Vertex[T]]]:
    pass


# TODO
# https://www.geeksforgeeks.org/detect-cycle-in-the-graph-using-degrees-of-nodes-of-graph/?ref=rp
def detct_cycle_using_degree(graph: Graph[T]) -> bool:
    pass


if __name__ == '__main__':
    graph1: Graph[str] = Graph()
    graph1.add_edge('A', 'B', reverse=False)
    graph1.add_edge('B', 'C', reverse=False)
    graph1.add_edge('C', 'D', reverse=False)

    print('Graph:')
    print(graph1, '\n')

    # (B-->A, A-->C, B-->C, C-->A, A-->B, C-->B)
    print("All edges:", graph1.edges)

    # (B---A, A---C, B---C)
    print("Undirected/unique edges:", graph1.undirected_edges)

    has_cycle = detect_cycle_using_disjoint_set(graph1)
    print("\nUsing Disjoint set - " +
Ejemplo n.º 10
0
 def __init__(self):
     self.graph = Graph()
     self.pages = []
Ejemplo n.º 11
0
# Encoding: UTF-8
"""
Run Graph program from CLI
Usage : python run.py {start_node} {end_node} {path/to/csv}
"""

from Graph.graph import Graph
from Converter.csv_converter import CsvConverter
import pprint
import argparse

# Get arg from CLI
argparser = argparse.ArgumentParser(description="Run Graph program from CLI")
argparser.add_argument('start_node', help="The start node for pathfinding")
argparser.add_argument('end_node', help="The end node for pathfinding")
argparser.add_argument('csv_file', help="csv file representing graph as : ['source', 'target', 'cost']")
args = argparser.parse_args()

graph = Graph()
graph.set_converter(CsvConverter())
graph.convert(args.csv_file)
print "Graph loaded :"
graph.print_graph()
path = graph.find_path(args.start_node, args.end_node)
pprint.pprint("A path exists from %s to %s" % (args.start_node, args.end_node))
pprint.pprint(path)
shortest_path = graph.djikstra(args.start_node, args.end_node)
print "And the minimum cost path is :"
pprint.pprint(shortest_path)
Ejemplo n.º 12
0
    # We could randomly start from any vertex and all __DFS__(random_vertex, visited) only once. But then, if graph
    # would be disconnected then, we might miss a few vertex while traversing the graph.
    for data, ver in all_data_vertex_mapping.items():
        if not visited.get(data, False):
            __DFS__(ver)
    return dfs


if __name__ == '__main__':
    # a -- b             x
    # |    |  \        /   \
    # |    |   e      y     z
    # |    |  /
    # c -- d

    graph1 = Graph()
    graph1.add_edge('a', 'b', is_directed=False)
    graph1.add_edge('b', 'e', is_directed=False)
    graph1.add_edge('b', 'd', is_directed=False)
    graph1.add_edge('e', 'd', is_directed=False)
    graph1.add_edge('d', 'c', is_directed=False)
    graph1.add_edge('c', 'a', is_directed=False)
    graph1.add_edge('x', 'y', is_directed=False)
    graph1.add_edge('x', 'z', is_directed=False)

    print(graph1)
    bfs_arr = BFS(graph1)
    # [b, a, e, d, c, x, z, y]
    print("\nBFS:", bfs_arr)

    dfs_arr = DFS_recursive(graph1)
Ejemplo n.º 13
0
 def __init__(self):
     self.trie = Trie()      # Only change Trie <-> Trie2 here to test the other class
     self.graph = Graph()
     self.pages = []
     self.dict = {}      # Dictionary is used to keep record of pages, in the format <PageNumber>:<PageName>
     self.files = []
    return distance_matrix, vertex_idx_mapping


if __name__ == '__main__':
    #
    #    ------> D <-------
    #   |      /           |
    # 15|    / 1           | 2
    #   | ⤶               |
    #   A -----> B -----> C
    #   |   3       -2    ▲
    #   |                 |
    #    -----------------
    #           6

    graph: Graph[str] = Graph()
    graph.add_edge('A', 'B', weight=3, is_directed=True)
    graph.add_edge('A', 'C', weight=6, is_directed=True)
    graph.add_edge('A', 'D', weight=15, is_directed=True)
    graph.add_edge('B', 'C', weight=-2, is_directed=True)
    graph.add_edge('C', 'D', weight=2, is_directed=True)
    graph.add_edge('D', 'A', weight=1, is_directed=True)

    print(graph)

    distance_matrix, vertex_idx_mapping = floyd_warshalls_all_pairs_shortest_path(
        graph)
    idx_vertex_mapping = {idx: v for v, idx in vertex_idx_mapping.items()}

    # V  A  B  C  D
    # A: 0  3  1  3
        for neighbor in current_vert.get_neighbors():
            # print(current_vert, neighbor)
            if queue.contains(neighbor.key):
                new_dist = current_vert.dist + current_vert.get_weight(neighbor)
                # print(new_dist, 'new dist')
                if new_dist < neighbor.dist:
                    neighbor.dist = new_dist
                    neighbor.predecessor = current_vert
                    # print(neighbor.predecessor)
                    #  The problem is herede
                    # queue.percolate_up(neighbor.key, queue.node_position[neighbor.key])
                    queue.percolate_up(queue.node_position[neighbor.key], neighbor.key)



g = Graph()
a = ['A', 'B', 'C', 'D', 'E']
for key in a:
    g.add_vertex(key)

g.add_edge('A', 'B', 3)
g.add_edge('B', 'A', 3)
g.add_edge('A', 'C', 2)
g.add_edge('C', 'A', 2)
g.add_edge('A', 'E', 4)
g.add_edge('E', 'A', 4)
g.add_edge('B', 'C', 8)
g.add_edge('C', 'B', 8)
g.add_edge('E', 'D', 3)
g.add_edge('D', 'E', 3)
g.add_edge('D', 'C', 1)
Ejemplo n.º 16
0
        head_node = head_node.next_element

    # remove the node from the recursive call
    rec_node_stack[node] = False
    return False


# g1 = Graph(4)
# g1.add_edge(0, 1)
# g1.add_edge(1, 2)
# g1.add_edge(1, 3)
# g1.add_edge(3, 0)
#
# g2 = Graph(3)
# g2.add_edge(0, 1)
# g2.add_edge(1, 2)

g3 = Graph(10)
g3.add_edge(0, 1)
g3.add_edge(0, 2)
g3.add_edge(1, 4)
g3.add_edge(1, 5)
g3.add_edge(2, 6)
g3.add_edge(2, 7)
g3.add_edge(3, 8)
g3.add_edge(3, 9)
g3.add_edge(9, 0)

# print(detect_cycle(g1))
# print(detect_cycle(g2))
print(detect_cycle(g3))
Ejemplo n.º 17
0
def check_cycle(g, node, visited, parent):
    # Mark node as visited
    visited[node] = True

    # Pick adjacent node and run recursive DFS
    adjacent = g.array[node].head_node
    while adjacent:
        if visited[adjacent.data] is False:
            if check_cycle(g, adjacent.data, visited, node) is True:
                return True

        # If adjacent is visited and not the parent node of the current node
        elif adjacent.data is not parent:
            # Cycle found
            return True
        adjacent = adjacent.next_element

    return False


g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(0, 3)
g.add_edge(3, 4)
g.add_edge(1, 0)
g.add_edge(2, 0)
g.add_edge(3, 0)
g.add_edge(4, 3)

print(is_tree(g))
Ejemplo n.º 18
0
    while not queue.is_empty():
        # Dequeue a vertex/node from queue and add it to result
        current_node = queue.dequeue()
        result += str(current_node)
        # Get adjacent vertices to the current_node from the list,
        # and if they are not already visited then enqueue them in the Q
        temp = g.array[current_node].head_node
        while temp is not None:
            if not visited[temp.data]:
                queue.enqueue(temp.data)
                visited[temp.data] = True  # Visit the current Node
            temp = temp.next_element
    return result


g = Graph(7)
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(2, 4)
g.add_edge(2, 5)
g.add_edge(3, 6)
print(bfs_traversal(g, 1))
# g = Graph(6)
#
# num_of_vertices = g.vertices
#
# if num_of_vertices == 0:
#     print("Graph is empty")
# else:
#     g.add_edge(0, 1)
#     g.add_edge(0, 2)
Ejemplo n.º 19
0
            return True

        # Continue BFS by obtaining first element in linked list
        adjacent = g.array[node].head_node
        while adjacent:
            # enqueue adjacent node if it has not been visited
            if visited[adjacent.data] is False:
                queue.enqueue(adjacent.data)
                visited[adjacent.data] = True
            adjacent = adjacent.next_element

    # Destination was not found in the search
    return False


g1 = Graph(9)
g1.add_edge(0, 2)
g1.add_edge(0, 5)
g1.add_edge(2, 3)
g1.add_edge(2, 4)
g1.add_edge(5, 3)
g1.add_edge(5, 6)
g1.add_edge(3, 6)
g1.add_edge(6, 7)
g1.add_edge(6, 8)
g1.add_edge(6, 4)
g1.add_edge(7, 8)

g2 = Graph(4)
g2.add_edge(0, 1)
g2.add_edge(1, 2)
Ejemplo n.º 20
0
#     # Reset all values in visited[] as false and do
#     # DFS beginning from v to check if all vertices are
#     # reachable from it or not.
#     visited = [False]*(g.vertices)
#     perform_DFS(g, last_v, visited)
#     if any(i is False for i in visited):
#         return -1
#     else:
#         return last_v
#
#
# # A recursive function to print DFS starting from v
# def perform_DFS(g, node, visited):
#
#     # Mark the current node as visited and print it
#     visited[node] = True
#
#     # Recur for all the vertices adjacent to this vertex
#     temp = g.array[node].head_node
#     while(temp):
#         if visited[temp.data] is False:
#             perform_DFS(g, temp.data, visited)
#         temp = temp.next_element


g = Graph(4)
g.add_edge(0, 1)
g.add_edge(1, 2)
g.add_edge(3, 0)
g.add_edge(3, 1)
print(find_mother_vertex(g))
Ejemplo n.º 21
0
def main():
    g = Graph(int(input("Enter Number Of Nodes of Your Graph: ")))
    g.create_graph_with_edges(int(
        input("Enter The Number Of Edges : ")))  # Take The Graph Input
    g.sort_edges_by_value()  # Sort The Edges By Weight
    krushkal_algo(g)