Question: ALGORITHM DFS ( G ) / / Implements a depth - first search traversal of a given graph / / Input: Graph G = V
ALGORITHM DFSG
Implements a depthfirst search traversal of a given graph
Input: Graph G VE
Output: Graph G with its vertices marked with consecutive integers
in the order they are first encountered by the DFS traversal
mark each vertex in V with as a mark of being unvisited
count
for each vertex v in V do
if v is marked with
dfsv
dfsv
visits recursively all the unvisited vertices connected to vertex v
by a path and numbers them in the order they are encountered
via global variable count
count count ; mark v with count
for each vertex w in V adjacent to v do
if w is marked with
dfsw
# graph.py
class Graph:
Super class for implementations of Graph
A Graph uses ints n to represent vertices, but also maintains
data structures to "translate" between vertices and a set of labels.
g Graphabc
glabel
a
gidb
This class should be subclassed to create a concrete implementation of
graphs eg with an adjacency matrix or an adjacency list
class Edge:
Edge is a record to supply edge information
def initself v v weight:
self.v v
self.v v
self.weight weight
def reprself:
return fEdgeselfvselfvselfweight
def initself vertexlabels, directedFalse:
Create empty graph from list of vertex labels strings
self.label vertexlabels
self.id label: id for id label in enumeratevertexlabels
self.nverts lenvertexlabels
self.nedges
self.directed directed
def verticiesself:
Return an iterator for label ids
return rangeselfnverts
def addlabeledgeself label label weight:
self.addedgeselfidlabel self.idlabel weight
# below are methods to be implemented in a subclass
def addedgeself v v weight:
Add the edge from v to v to the graph
raise NotImplementedError
def edgeself v v:
Returns an Edge object if edge v v is in graph, otherwise None
Can be used as an existence test
e gedgev v
if e:
# edge exists
raise NotImplementedError
def edgesself vertexNone:
Returns an iterator over Edge objects
If vertex is None the iterator supplies all edges of the
graph. When vertex is supplied, it iterates over edges from
that vertex ie the adjacency list
raise NotImplementedError
def deleteedgeself v v:
Deletes the edge. Does nothing if the edge does not exist
raise NotImplementedError
# Example start of subclass should be in matrixgraph.py
class MatrixGraphGraph:
def initself labels, directed:
superinitlabels directed
# other initialization here
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
