pangfengliu / programmingtasks

programming tasks from my courses
67 stars 17 forks source link

Hamiltonian Cycle #363

Open littlehug opened 5 years ago

littlehug commented 5 years ago

Write a program to find a cycle in a network of cities.

Task Description

We are given a set of cities (indexed from 0 to N - 1) and roads in which a road connects two cities. You need to find a cycle of roads that visits each city exactly once. There could be many solutions so you need to output the cycle with the least dictionary order. If there is no such cycle, output “NO SOLUTION”.

Let us illustrate the task with an examples. There are five cities and seven roads as in the following figure. Both 0-1-2-3-4-0 and 0-1-4-3-2-0 are cycles that go through each city exactly once, but we need to output 0-1-2-3-4-0 as the solution because it has smallest dictionary order.

figure

Subtask