-
Notifications
You must be signed in to change notification settings - Fork 89
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
""" | ||
Given a directed graph, design an algorithm to find out whether there is a route between two nodes. | ||
Example | ||
Given graph: | ||
A----->B----->C | ||
\ | | ||
\ | | ||
\ | | ||
\ v | ||
->D----->E | ||
for s = B and t = E, return true | ||
for s = D and t = C, return false | ||
""" | ||
__author__ = 'Daniel' | ||
|
||
|
||
class DirectedGraphNode: | ||
def __init__(self, x): | ||
self.label = x | ||
self.neighbors = [] | ||
|
||
|
||
class Solution(object): | ||
def hasRoute(self, graph, s, t): | ||
visited = set() | ||
return self.dfs(s, t, visited) | ||
|
||
def dfs(self, s, t, visited): | ||
"""pre-check""" | ||
if s == t: | ||
return True | ||
|
||
visited.add(s) | ||
for nbr in s.neighbors: | ||
if nbr not in visited: | ||
if self.dfs(nbr, t, visited): | ||
return True | ||
|
||
return False | ||
|