Q. Which are the two standard ways of traversing a graph? Explain them with an example of each.
Ans:
The two ways of traversing a graph are written below
i. The depth-first traversal of a graph is same as the depth-first traversal of a tree. Since a graph does not have any root, when we do a depth-first traversal, we must specify the vertex at which to begin. Depth-first traversal of a graph visits a vertex and then recursively visits all the vertices adjacent to that particular node. The catch is that the graph may have cycles, but the traversal must visit each and every vertex at most once. The solution to the trouble is to keep track of the nodes that have been visited, so that the traversal does not undergo the fate of infinite recursion.
ii. The breadth-first traversal of a graph is same as the breadth-first traversal of the tree. Breadth-first tree traversal first of all visits all the nodes at the depth zero (which is the root), then it visits all the nodes at depth one, and this process continues. Since a graph does not has root, when we perform a breadth-first traversal, we should specify the vertex at which to start the traversal. Furthermore, we can define the depth of the given vertex to be the length of the shortest path from the starting vertex to the vertex given to us.
Hence, breadth-first traversal first visits the beginning vertex, then all the vertices adjacent to the starting vertex, and the all the vertices adjacent to those, and it continues.