示例#1
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')
示例#2
0
#!/usr/bin/env python3
from math import sqrt
from common import IO
from graph.weighted import GraphMatrix, Edge
from graph import algorithm

io = IO()

N = int(io.readline())
coords = []
G = GraphMatrix(N, 0, [])
for i in range(N):
    x, y = map(float, io.readline().split())
    coords.append((x, y))
    for j, (x2, y2) in enumerate(coords):
        dist = sqrt((x2 - x) ** 2 + (y2 - y) ** 2)
        G.add_edge(Edge(i, j, dist))


io.section('TSP path')
weight, path = algorithm.TSP(G)
if path is not None:
    io.print('TSP path with weight {} found:'.format(weight))
    io.print_path(path)
else:
    io.print('TSP path not found')