Created
January 25, 2015 18:36
-
-
Save sujayy1983/d62672e531e14de9e320 to your computer and use it in GitHub Desktop.
Depth First Search
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
""" | |
@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