Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added DFS code in python #62

Merged
merged 1 commit into from
Oct 2, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions Python implementation DataStructures/dfs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import collections

class Graph:
def __init__(self):
self.adjList = collections.defaultdict(set)

def addEdge(self, node1, node2):
self.adjList[node1].add(node2)
self.adjList[node2].add(node1)

def dfsHelper(current, graph, visited, visitFunc):
if (visited[current]):
return

visited[current] = True;

visitFunc(current)

for neighbor in graph.adjList[current]:
dfsHelper(neighbor, graph, visited, visitFunc)


def dfs(current, graph, visitFunc):
visited = collections.defaultdict(bool)
dfsHelper(current, graph, visited, visitFunc)

def visitPrint(i):
print(i)

# Testing the depth first search implementation
if __name__ == "__main__":

# Testing on this tree
# 1
# / \
# / \
# 2 3
# / \ / \
# 4 5 6 7

g = Graph()
g.addEdge(1, 2)
g.addEdge(1, 3)
g.addEdge(2, 4)
g.addEdge(2, 5)
g.addEdge(3, 6)
g.addEdge(3, 7)

print("Test 1:")
dfs(1, g, visitPrint)

print("\nTest2:")
dfs(2, g, visitPrint)