Skip to content

Commit

Permalink
dfs
Browse files Browse the repository at this point in the history
  • Loading branch information
idf committed Nov 6, 2015
1 parent 77265d0 commit d6a3e3a
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions Route Between Two Nodes in Graph.py
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

0 comments on commit d6a3e3a

Please sign in to comment.