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

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

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

Post 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
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply