def main():
    args = parse_arguments()

    # Start measuring execution time
    begin_time = timeit.default_timer()

    # Read graph
    input_file = open(args.input, 'r')

    graph = networkx.Graph()

    number_of_vertices, number_of_edges = [int(x) for x in input_file.readline().split()]
    if args.naive:
        graph.add_nodes_from(range(1, number_of_vertices + 1), colour=utils.Colours.red)
    else:
        graph.add_nodes_from(range(1, number_of_vertices + 1), colour=utils.Colours.grey)

    for i in range(number_of_edges):
        vertex1, vertex2 = [int(x) for x in input_file.readline().split()]
        graph.add_edge(vertex1, vertex2)

    # Find solution
    if args.naive:
        graph = naive.naive(graph)
    elif args.greedy:
        graph = greedy.greedy(graph, args.image_path)
    elif args.simul:
        graph = simultaneous_greedy.simultaneous_greedy(graph, args.image_path)
    else:
        greedy_solution = greedy.greedy(graph.copy(), args.image_path)
        simul_solution = simultaneous_greedy.simultaneous_greedy(graph, args.image_path)
        if utils.get_colours_use(greedy_solution)[2] > utils.get_colours_use(simul_solution)[2]:
            graph = greedy_solution
        else:
            graph = simul_solution

    # Print results
    output_file = open(args.output, 'w')

    # Check whether a solution was found
    if graph:
        output_file.write(' '.join(map(str, utils.get_colours_use(graph))[:3]) + '\n')
        for node in graph.nodes(data=True):
            output_file.write(str(node[0]) + ' ' + node[1]['colour'].name + '\n')
    else:
        output_file.write('Cannot find colouring')

    # Cleanup
    input_file.close()
    output_file.close()

    # Stop measuring execution time
    execution_time = timeit.default_timer() - begin_time

    if args.time:
        print(execution_time)
Пример #2
0
def naive(graph):
    """
        Solves problem using naive algorithm. Returns None if solution does not exist.

        :return: networkx.Graph
    """
    # Check if solution exist
    for node in graph.nodes():
        if graph.degree(node) == 0:
            return None

    best_coloured_graph = None
    grey_colour_uses = -1

    while not is_final_condition(graph):
        if utils.get_colours_use(graph)[2] > grey_colour_uses and utils.is_properly_coloured(graph):
            best_coloured_graph = graph.copy()
            grey_colour_uses = utils.get_colours_use(graph)[2]
        next_colouring(graph)

    return best_coloured_graph