Leg dit BFS algoritme in java stap voor stap uit: import java.util.*; class Graph {…
- User
Leg dit BFS algoritme in java stap voor stap uit: import java.util.*;
class Graph { private int vertices; private LinkedList[] adjacencyList;
// Constructor Graph(int v) { vertices = v; adjacencyList = new LinkedList[v]; for (int i = 0; i < v; i++) { adjacencyList[i] = new LinkedList<>(); } } // Add an edge to the graph void addEdge(int v, int w) { adjacencyList[v].add(w); } // BFS traversal starting from source vertex s void BFS(int s) { // Mark all vertices as not visited (false by default) boolean[] visited = new boolean[vertices]; // Create a queue for BFS LinkedList<Integer> queue = new LinkedList<>(); // Mark the current node as visited and enqueue it visited[s] = true; System.out.println("Starting BFS from vertex " + s); queue.add(s); while (!queue.isEmpty()) { // Dequeue a vertex from queue and print it s = queue.poll(); System.out.print(s + " "); // Get all adjacent vertices of the dequeued vertex s // If an adjacent vertex has not been visited, mark it // visited and enqueue it for (int adjacent : adjacencyList[s]) { if (!visited[adjacent]) { visited[adjacent] = true; queue.add(adjacent); } } } } // Main method to demonstrate BFS public static void main(String[] args) { Graph g = new Graph(6); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(2, 4); g.addEdge(2, 5); System.out.println("Breadth First Traversal (starting from vertex 0):"); g.BFS(0); }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.