Created
June 5, 2021 23:03
-
-
Save deedee47/0b89cfdf224d90faff061287774e57d0 to your computer and use it in GitHub Desktop.
Detects if there is at least a cyclic path in all available routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public boolean isThereCycle(Map<Character, List<Character>> map){ | |
if(map == null || map.isEmpty()) return false; | |
//use each node as starting point | |
for(char item : map.keySet()){ | |
//create new tracking experience for each start point | |
Stack<Character> trackPad = new Stack<>(); | |
List<Character> visitedPoints = new ArrayList<>(); | |
visitedPoints.add(item); | |
trackPad.addAll(map.get(item)); | |
while(!trackPad.isEmpty()){ | |
char subItem = trackPad.pop(); | |
//check if subpath leads back to origin | |
//if key is not found, return a default list - handles null exceptions | |
if(map.getOrDefault(subItem, new ArrayList<>()).contains(item)) return true; | |
//avoid re-processing a path | |
if(!visitedPoints.contains(subItem)){ | |
trackPad.addAll(map.getOrDefault(subItem, new ArrayList<>())); | |
visitedPoints.add(subItem); | |
} | |
} | |
} | |
return false; | |
} |
Hi @meekgeek, true, I agree the use case is valid. Surprisingly it returns true when i debugged it with the example. Thanks for the feedback
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @deedee47, thank you for participating in Week 9 of #AlgorithmFridays.
Your solution is clean, easy to read for the most part and passes some of the test cases. One test case it doesn't pass however is when there is a path leading out from a node back to itself.
Here is an example:
In the above instance, there is a path leading from
A
back toA
so it should returntrue
. Is there a chance you made an assumption that this was not possible? Let me know what you think!But in all, this was a good attempt and you demonstrated good knowledge of solving graph traversal problems and using the Stack data structure. Really neat!