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

Iterative Depth First Traversal of Graph #122

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
60 changes: 60 additions & 0 deletions Python/Iterative Depth First Traversal of Graph
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# An Iterative Python program to do DFS traversal from
# a given source vertex. DFS(int s) traverses vertices
# reachable from s.

# This class represents a directed graph using adjacency
# list representation
class Graph:
def __init__(self,V): # Constructor
self.V = V # No. of vertices
self.adj = [[] for i in range(V)] # adjacency lists

def addEdge(self,v, w): # to add an edge to graph
self.adj[v].append(w) # Add w to v’s list.


# prints all not yet visited vertices reachable from s
def DFS(self,s): # prints all vertices in DFS manner from a given source.
# Initially mark all verices as not visited
visited = [False for i in range(self.V)]

# Create a stack for DFS
stack = []

# Push the current source node.
stack.append(s)

while (len(stack)):
# Pop a vertex from stack and print it
s = stack[-1]
stack.pop()

# Stack may contain same vertex twice. So
# we need to print the popped item only
# if it is not visited.
if (not visited[s]):
print(s,end=' ')
visited[s] = True

# Get all adjacent vertices of the popped vertex s
# If a adjacent has not been visited, then push it
# to the stack.
for node in self.adj[s]:
if (not visited[node]):
stack.append(node)



# Driver program to test methods of graph class

g = Graph(5); # Total 5 vertices in graph
g.addEdge(1, 0);
g.addEdge(0, 2);
g.addEdge(2, 1);
g.addEdge(0, 3);
g.addEdge(1, 4);

print("Following is Depth First Traversal")
g.DFS(0)

# This code is contributed by Mehraj