Breadth First Search (BFS) is a graph traversal algorithm that visits all vertices of a graph in breadth-first order, i.e., it visits all vertices at a certain distance before visiting vertices at a greater distance.
Here's the Java code for BFS in an undirected graph:
import java.util.*;
class BFS {
private int V; // No. of vertices
private LinkedList<Integer> adj[]; //Adjacency List
// Constructor
BFS(int v) {
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
// Function to add an edge into the graph
void addEdge(int v,int w) {
adj[v].add(w);
}
// prints BFS traversal from a given source s
void BFS(int s) {
// Mark all the vertices as not visited(By default
// set as false)
boolean visited[] = new boolean[V];
// Create a queue for BFS
LinkedList<Integer> queue = new LinkedList<Integer>();
// Mark the source node as visited and enqueue it
visited[s]=true;
queue.add(s);
while (queue.size() != 0)
{
// 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 a adjacent has not been visited, then mark it
// visited and enqueue it
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
// Driver method to
public static void main(String args[])
{
BFS g = new BFS(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("Following is Breadth First Traversal "+
"(starting from vertex 2)");
g.BFS(2);
}
}
This code uses an adjacency list to represent the graph, with each index of the list representing a vertex, and the elements in the list representing the vertices adjacent to that vertex. The BFS method implements the BFS algorithm, starting from the source vertex s. It uses a boolean array visited to keep track of which vertices have been visited, and a queue to store the vertices to be visited. The method repeatedly dequeues a vertex from the queue, marks it as visited, and adds its unvisited neighbors to the queue.
Here's the sample output for the above code:
Following is the output of the code:
Following is Breadth First Traversal (starting from vertex 2)
2 0 3 1
In this example, the graph has 4 vertices and the BFS algorithm is started from vertex 2. The output shows the order in which the vertices were visited during the BFS.
Time complexity of BFS is O(V+E), where V is the number of vertices and E is the number of edges in the graph. This is because in the worst case, all vertices and edges will be visited and processed.
Space complexity of BFS is O(V), where V is the number of vertices in the graph. This is because the space required to store the vertices to be visited in the queue is proportional to the number of vertices.
Comentarios