Welcome to our comprehensive guide on BFS (Breadth-First Search) for Connected Components! This lesson is designed for both beginners and intermediate learners, and we'll walk you through this fascinating topic step-by-step. Let's dive in!
In graph theory, a connected graph is one in which there is a path between every pair of vertices. A graph that is not connected can be divided into disjoint subgraphs, each of which is connected. These subgraphs are called the connected components of the graph.
BFS is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node in the number of trees) and explores all of the neighbor nodes at the present depth prior to moving on to nodes at the next depth level.
def connected_components(graph, visited=None):
if not visited:
visited = [False] * len(graph)
def bfs(node):
visited[node] = True
queue.append(node)
while queue:
current = queue.pop(0)
for neighbor in graph[current]:
if not visited[neighbor]:
visited[neighbor] = True
queue.append(neighbor)
for i in range(len(graph)):
if not visited[i]:
bfs(i)
return visited.count(True)function connectedComponents(graph, visited = new Array(graph.length).fill(false)) {
function bfs(node) {
visited[node] = true;
queue.push(node);
while (queue.length > 0) {
const current = queue.shift();
for (let neighbor of graph[current]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.push(neighbor);
}
}
}
}
for (let i = 0; i < graph.length; i++) {
if (!visited[i]) {
bfs(i);
}
}
return visited.reduce((count, val) => count + val);
}What is the main difference between DFS and BFS?
By now, you should have a good understanding of how BFS can be used to find the connected components in a graph. Keep practicing, and happy coding! šš»š