Here's a simple implementation using HashMaps in Java:
String[][] paths = { {"P", "B"}, {"B", "M"}, {"O", "P"}, {"M", "Z"}, }; // create a single hash map, mapping start->end HashMap<String, String> end = new HashMap<>(); for(int i = 0; i < paths.length; i++) { end.put(paths[i][0], paths[i][1]); } // find if a cycle exists String origin = null; for (String key : end.keySet()) { if(!end.containsValue(key)) { origin = key; break; } } if(origin == null) { System.out.println("cycle exists"); return; // no origin found, cycle exists } // iterate over hash map: int count = 0; while(true) { if(!end.containsKey(origin)) break; String next = end.get(origin); System.out.println(origin + " " + next); origin = next; if(++count > paths.length) { System.out.println("cycle exists"); break; } }
end saves the end point (value) based on the start point (key).
If a point exists as a start point, but not an end point, it will be the key in end , but not the value in end . Thus, iterating over the key set end and checking whether end contains each key, how the value will find the beginning. If there is no such origin, then there is a cycle. However, this is not enough to determine if a cycle exists, because a cycle may exist, even if there is an origin. Consider this set:
PBBM OP MZ ZM
There is a unique origin (O), but there is also a cycle M β Z β M. To discover this, you can walk around the set and follow what you have already visited, or, more simply, you can walk the set, and if you are in in the end, you visit more points than the input length, then there should be a cycle.
To go through the set, set the line to the origin. Then continue looking for the value at end indicated by origin as the key, and print the key, value pair (origin, end.get (origin)) as the beginning, the end. Then set end.get (origin) as the new source. The loop ends when there is no value for the current source at the end of the HashMap.
This algorithm fails if there are duplicate start or end positions in the list, for example:
PBBM OP MZ BZ
It is unclear whether you need to handle this case.