Breadth-First Search (BFS)
is a fundamental graph traversal algorithm. It explores the graph level by level, starting from a given source node and expanding outwards to all its neighbours before moving on to the next level.
INPUT :
[
[0, 1, 1, 0],
[0, 0, 1, 0],
[1, 0, 0, 1],
[0, 0, 0, 1]
] , 2
OUTPUT:
2 ->
0 ->
1 ->
3
directed
and undirected
) as well as trees.Time Complexity: O(V + E)
Space Complexity: O(V)
https://drawtocode.vercel.app/problems/breadth-first-search
Loading component...
Loading component...
INPUT: [ 0 ->[ 1, 2 ] , 1 -> [2] , 2 -> [ 0 , 3], 3 -> [3] ] , 2 , 4
OUTPUT: 2,0,1,3
public static void main(String[] args) {
int numVertices = 6;
List<Integer>[] graph = new ArrayList[numVertices];
for (int i = 0; i < numVertices; i++) {
graph[i] = new ArrayList<>();
}//Loop End
graph[0].add(1);
graph[0].add(2);
graph[1].add(0);
graph[1].add(3);
graph[1].add(4);
graph[2].add(0);
graph[2].add(5);
graph[3].add(1);
graph[4].add(1);
graph[4].add(5);
graph[5].add(2);
graph[5].add(4);
System.out.println("BFS starting from node 0:");
bfs(graph, 0, numVertices);
} //Function End
public static void bfs(List<Integer>[] graph, int start, int numVertices) {
boolean[] visited = new boolean[numVertices];
Queue<Integer> queue = new LinkedList<>();
visited[start] = true;
queue.add(start);
while (!queue.isEmpty()) {
int current = queue.poll();
System.out.print(current + " ");
for (int neighbor : graph[current]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);
}//If End
}//Loop End
}//Loop End
}//function end
Utility Function is not required.