CC-4 : Implement Bi-directional/ Undirectional graph Depth First (DFS) traversal.
Description:
Create and test a unidirectional Graph DFS Traversal program.Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
|
GraphDfs gph=new GraphDfs(5); gph=new GraphDfs(5); gph.addEdge(0, 2); gph.addEdge(0, 3); gph.addEdge(0, 1); gph.addEdge(2, 4); gph.displayGraph(); gph.dfsTraversal(0); System.out.println(); System.out.println("Dfs Traversal: "+ gph.dfsTraversal); |
vertex 0->2->3->1 vertex 1->0 vertex 2->0->4 vertex 3->0 vertex 4->2 Dfs Traversal: 0 2 4 3 1 |
Pseudocode:
| Initialize an int variable named visited to store information whether a particular vertice in the graph has been visited. |
| Initialize a String variable named dfsTraversal to hold output of DFS traversal of the graph. |
Method dfsTraversal(int vertex):
| Set visited[vertex] to 1. |
| Add vertex to dfsTraversal String as it has been traversed now. |
| Extract vertices connected to vertex from the adjacencyList. |
| Iterate through vertices connected to current vertex using iterator:
Set variable adjacentNode to point to current connected vertice in the iterator.
If visited[adjacentNode] is not 1, then:
Call dfsTraversal(adjacentNode) recursively.
|
Code:
public class GraphDfs {
private int vertices;
private ArrayList<ArrayList<Integer>> adjacencyLists=new ArrayList<ArrayList<Integer>>();
private int[] visited;
String dfsTraversal=new String();
public GraphDfs(int vertices) {
this.vertices=vertices;
visited=new int[vertices];
for (int iIdx=0; iIdx < vertices; iIdx++) {
adjacencyLists.add(new ArrayList<Integer>());
visited[iIdx]=0;
}
}
public void addEdge(int source, int dest) {
adjacencyLists.get(source).add(dest);
adjacencyLists.get(dest).add(source);
}
public void dfsTraversal(int vertex) {
visited[vertex]=1;
dfsTraversal+= vertex + " ";
Iterator<Integer> itr=adjacencyLists.get(vertex).iterator();
while (itr.hasNext()) {
int adjacentNode=itr.next();
if (visited[adjacentNode]==0) {
dfsTraversal(adjacentNode);
}
}
}
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |