l. Write a class DepthFirstPaths.java to implement a Depth First Search algorith
ID: 3807326 • Letter: L
Question
l. Write a class DepthFirstPaths.java to implement a Depth First Search algorithm using the pseudocode given below. Alternatively you can download the file Depth FirstPaths.java and implement all the unimplemented methods of the class so that it performs Depth First Search on graph G. See the pseudocode given below. DFS (G) 1 for each vertex u E G. V u color WHITE NIL 4 time 0 5 for each vertex u e G. V if color WHITE DFS-VISIT(G, u) DFS-VISIT (G,u) 1 time time 1 ll white vertex u has just been discovered 2 u.d time 3 u color GRAY ll explore edge (u, v) 4 for each v e G.Adilu] 5 if v color WHITE DFS-VISIT(G,v) 8 u color BLACK ll blacken u; it is finished 9 time time 1 10 time 2. Write driver program, which reads input file mediumG.txt as an undirected graph and runs the Depth First Search algorithm to find paths to all the other vertices considering 0 as the source. This driver program should display the paths in the following manner: 0 to v: "list of all the vertices traversed to go to v from 0, separated byExplanation / Answer
Ans::
program:
//DepthFirstPaths.java
public class DepthFirstPaths {
//booleann
private boolean[] marked;
private int[] edgeTo;
// source_verex
private final int s;
// graph G int s
public DepthFirstPaths(Graph G, int s) {
this.s = s;
edgeTo = new int[G.V()];
marked = new boolean[G.V()];
validateVertex(s);
dfs(G, s);
}
// depth_first_search from "v"
private void dfs(Graph G, int v) {
marked[v] = true;
for (int w : G.adj(v)) {
if (!marked[w]) {
edgeTo[w] = v;
dfs(G, w);
}
}
}
//path
public boolean hasPathTo(int v) {
validateVertex(v);
//return
return marked[v];
}
//iterabl
public Iterable<Integer> pathTo(int v) {
validateVertex(v);
// doesnt has path
if (!hasPathTo(v))
// returns_nul
return null;
Stack<Integer> path = new Stack<Integer>();
// for loop
for (int x = v; x != s; x = edgeTo[x])
// push
path.push(x);
path.push(s);
// return
return path;
}
// throws an IllegalArgumentException if unless the {@code 0 <= v < V}
private void validateVertex(int v) {
int V = marked.length;
if (v < 0 || v >= V)
throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
}
// driver progrm
public static void main(String[] args) {
In in = new In(args[0]);
Graph G = new Graph(in);
int s = Integer.parseInt(args[1]);
DepthFirstPaths dfs = new DepthFirstPaths(G, s);
for (int v = 0; v < G.V(); v++) {
if (dfs.hasPathTo(v)) {
StdOut.printf("%d to %d: ", s, v);
for (int x : dfs.pathTo(v)) {
if (x == s) StdOut.print(x);
else
StdOut.print("-" + x);
}
StdOut.println();
}
else {
StdOut.printf("%d to %d: not connected ", s, v);
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.