Page 1 of 1

public class GraphTraversal { // Representation of a directed graph using adjacency list public static void main(String[

Posted: Fri May 20, 2022 1:45 pm
by answerhappygod
public class GraphTraversal {
// Representation of a directed graph using adjacency list
public static void main(String[] args) {
DiGraph g = new DiGraph(10);
g.addEdge(1, 0);
g.addEdge(0, 2);
g.addEdge(2, 1);
g.addEdge(0, 3);
g.addEdge(1, 4);
g.addEdge(4, 5);
g.addEdge(4, 6);
g.addEdge(4, 7);
g.addEdge(6, 7);
g.addEdge(6, 8);
g.addEdge(8, 9);
g.addEdge(9, 9);
g.printGraph();
System.out.println("Depth First Search visit order: ");
g.DFS(0);
System.out.println();
System.out.println("Breadth First Search visit order: ");
g.BFS(0);
}
}
class DiGraph {
int V; // Number of Vertices
LinkedList<Integer> adj[]; // adjacency lists
// Constructor
DiGraph(int V) {
this.V = V;
adj = new LinkedList[V];
for (int i = 0; i < adj.length; i++)
adj = new LinkedList<Integer>();
}
// To add an edge to graph
void addEdge(int v, int w) {
adj[v].add(w); // Add w to v’s list.
}
void DFS(int s) {
// Write the proper code for DFS
}
void BFS(int s) {
// Write the proper code for BFS
}
public void printGraph() {
for (int src = 0; src < adj.length; src++) {
System.out.print(src);
for (Integer dest : adj[src]) {
System.out.print(" -> " + dest);
}
System.out.println();
}
}
}
1. Write the proper code to implement BFS
method in the program of the Example section
please write the answer in java