Skip to content

Instantly share code, notes, and snippets.

@sujayy1983
Created January 25, 2015 18:36
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 sujayy1983/d62672e531e14de9e320 to your computer and use it in GitHub Desktop.
Save sujayy1983/d62672e531e14de9e320 to your computer and use it in GitHub Desktop.
Depth First Search
"""
@Author: Sujayyendhiren Ramarao Srinivasamurthi
@Description: My implementation of DFS
"""
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def backtrack( parent , start, end ):
res = [ end ]
node = parent[res[-1]]
while node != start:
res.append( node )
node = parent[res[-1]]
res.append(start)
res.reverse()
return res
def dfs(start, end):
queue = []
visited = {}
parent = {}
node = start
queue.append(start)
while queue:
node = queue.pop(0)
if( node != end):
adjNodes = graph.get(node,[])
for adj in adjNodes:
if adj not in visited:
queue.insert( 0, adj )
visited[adj] = adj
parent[adj] = node
else:
return backtrack( parent, start, end)
if __name__ == '__main__':
print dfs( '1', '11' )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment