Python/graphs/depth_first_search_2.py
Sanders Lin 7aaf79cc23
Initialize set with source in DFS (#1872)
* Update dfs.py

* Add type hints, rearrange doc-strings and comments

* fixup! Format Python code with psf/black push

* dfs -> depth_first_search

Co-Authored-By: Christian Clauss <cclauss@me.com>

* dfs -> depth_first_search

* Add doctest for DFS

* fixup! Format Python code with psf/black push

* Rename dfs.py to depth_first_search_dictionary.py

* updating DIRECTORY.md

* Rename depth_first_search_dictionary.py to depth_first_search_dfs.py

* updating DIRECTORY.md

* Rename depth_first_search.py to depth_first_search_2.py

* updating DIRECTORY.md

* Rename depth_first_search_dfs.py to depth_first_search.py

* updating DIRECTORY.md

Co-authored-by: John Law <johnlaw.po@gmail.com>
Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
2020-04-17 20:05:29 +02:00

66 lines
1.6 KiB
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/python
""" Author: OMKAR PATHAK """
class Graph:
def __init__(self):
self.vertex = {}
# for printing the Graph vertices
def printGraph(self):
print(self.vertex)
for i in self.vertex.keys():
print(i, " -> ", " -> ".join([str(j) for j in self.vertex[i]]))
# for adding the edge between two vertices
def addEdge(self, fromVertex, toVertex):
# check if vertex is already present,
if fromVertex in self.vertex.keys():
self.vertex[fromVertex].append(toVertex)
else:
# else make a new vertex
self.vertex[fromVertex] = [toVertex]
def DFS(self):
# visited array for storing already visited nodes
visited = [False] * len(self.vertex)
# call the recursive helper function
for i in range(len(self.vertex)):
if visited[i] == False:
self.DFSRec(i, visited)
def DFSRec(self, startVertex, visited):
# mark start vertex as visited
visited[startVertex] = True
print(startVertex, end=" ")
# Recur for all the vertices that are adjacent to this node
for i in self.vertex.keys():
if visited[i] == False:
self.DFSRec(i, visited)
if __name__ == "__main__":
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
g.printGraph()
print("DFS:")
g.DFS()
# OUTPUT:
# 0  ->  1 -> 2
# 1  ->  2
# 2  ->  0 -> 3
# 3  ->  3
# DFS:
#  0 1 2 3