public class GraphTraversal { // Representation of a directed graph using adjacency list public static void main(String[
Posted: Fri May 20, 2022 12:36 pm
question in Java
1. Write the proper code to implement BFS method in the
program of the Example section
2. Rewrite the above program so it can represent
undirected graphs.
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); .addEdge (4, 7); .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(O); System.out.println(); System.out.println("Breadth First search visit order: "); g.BFS(O); } } 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(); } } }