Esempio n. 1
0
def eulerian_cycle(G: DirectedGraphMatrix) -> list:
    """
    Find eulerian cycle in the given graph
    Args:
        graph to find eulerian cycle in
    Return:
        path of the cycle if found or None if not found
    """

    def selfloop(u: int):
        nonlocal G
        path = []
        cur = u
        while cur != u or not path:
            path.append(cur)
            (v, c) = G.adj(cur).__next__()
            G.remove_edge(DirectedEdge(cur, v))
            cur = v
        path.append(u)
        return path

    G = deepcopy(G)
    E = G.E()
    tour = [0]
    cur = 0
    while cur < len(tour):
        try:
            G.adj(tour[cur]).__next__()
            tour = tour[:cur] + selfloop(tour[cur]) + tour[cur + 1:]
        except StopIteration:
            cur += 1
    return tour if len(tour) == E + 1 else None
Esempio n. 2
0
#!/usr/bin/env python3
from common import IO
from graph.directed import Graph, GraphMatrix
from graph import algorithm

io = IO()

G = Graph.fromfile(io.filein)
G_matrix = GraphMatrix.from_graph(G)

# Eulerian cycle, part 1
io.section('Eulerian cycle')
eulerian_cycle = algorithm.eulerian_cycle(G_matrix)
if eulerian_cycle is not None:
    io.print('Eulerian cycle found: ')
    io.print_path(eulerian_cycle)
else:
    io.print('Eulerian cycle not found!')

    # Eulerian path, part 2
    io.section('Eulerian path')
    eulerian_path = algorithm.eulerian_path(G_matrix)
    if eulerian_path is not None:
        io.print('Eulerian path found: ')
        io.print_path(eulerian_path)
    else:
        io.print('Eulerian path not found!')


# Hamiltonian cycle, part 1
io.section('Hamiltonian cycle')