Find a available path from a given source to a given destination in a given graph.
Intuition
Use DFS to find all reachable nodes and check if the destination lie within those nodes.
Approach
We first transform the adjacency matrix to adjacency list to make BFS easier, then we use
a queue to maintain the reachable nodes, to prevent from cycling, we also use a set to keep track of visited nodes.
If at any point, we reach the destination
, we return directly.
Complexity
Time complexity: iterate all nodes at most once $$O(n)$$
Space complexity: stores nodes of the same distance in the graph to the source $$O(n)$$
Code
|
|