Skip to content

Instantly share code, notes, and snippets.

@Fredpwol
Last active June 10, 2021 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fredpwol/9f87382b6cc2cb8a6cd1624db91dbbfb to your computer and use it in GitHub Desktop.
Save Fredpwol/9f87382b6cc2cb8a6cd1624db91dbbfb to your computer and use it in GitHub Desktop.
Find if a graph contains cycle
def depth_first_search(map, key, visited):
if key == None: return None
key = key.lower() if key.lower() in map else key.upper()
if not key in map: return False
if map[key] == None: return False
for point in map[key]:
if point.lower() in visited:
return True
visited.add(key.lower())
if depth_first_search(map, point, visited):
return True
visited = set()
return False
def find_cycle(map):
if map == None: return False
for point in map:
if depth_first_search(map, point, set()):
return True
return False
@meekg33k
Copy link

meekg33k commented Jun 10, 2021

Hello @Fredpwol, thank you for participating in Week 9 of #AlgorithmFridays.

Your solution is clean and easy to read and works for most of the test cases. However it fails the test cases for when any of the adjacent paths to a path has no paths leading out from it (something called a leaf node in Computer science terms).

Here is an example:

map = { 'C': ['A', 'B'] } # 'A' and 'B' have no paths leading out from them

In the above instance, A and B are leaf nodes because there is no path out from them and this is where your solution breaks - specifically on line 4. Ideally there should be a check to see if A or B is a key in the map, something like if key in map

But in all, this was a good attempt and you demonstrated good knowledge of depth first search for solving recursive problems. Kudos to you!

Looking forward to hearing your thoughts.

@Fredpwol
Copy link
Author

Hello @meekg33k, Thank you for the feedback I totally overlooked the edge case for leave nodes. I have updated my code to handle that edge case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment