⬅ Previous Topic
Number of Provinces in an Undirected GraphNext Topic ⮕
Rotten Oranges Problem - BFS in Matrix⬅ Previous Topic
Number of Provinces in an Undirected GraphNext Topic ⮕
Rotten Oranges Problem - BFS in MatrixTopic Contents
The Connected Components in a Matrix problem involves identifying clusters of connected 1s in a binary matrix. Two 1s are considered connected if they are adjacent vertically or horizontally (not diagonally).
The task is to count how many such distinct connected groups (components) exist in the matrix.
visited
matrix of the same size as the input matrix, filled with false
.1
and is not visited:function countConnectedComponents(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
const visited = Array.from({ length: rows }, () => new Array(cols).fill(false));
let components = 0;
const directions = [
[0, 1], [1, 0], [0, -1], [-1, 0] // right, down, left, up
];
function dfs(r, c) {
if (
r < 0 || c < 0 || r >= rows || c >= cols ||
visited[r][c] || matrix[r][c] === 0
) return;
visited[r][c] = true;
for (const [dr, dc] of directions) {
dfs(r + dr, c + dc);
}
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (matrix[i][j] === 1 && !visited[i][j]) {
components++;
dfs(i, j);
}
}
}
return components;
}
console.log(countConnectedComponents([
[1,1,0,0],
[0,1,0,0],
[1,0,0,1],
[0,0,1,1]
])); // Output: 2
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(m * n) | Every cell in the matrix must be visited at least once to ensure no 1s are missed, even if all values are 0. |
Average Case | O(m * n) | Each cell is visited once; for every new component, we run DFS/BFS from the unvisited 1. |
Worst Case | O(m * n) | In the worst case, the matrix is filled with 1s, and every cell is part of a single large component traversed by DFS/BFS. |
O(m * n)
Explanation: A visited matrix of the same size is used to keep track of explored cells.
⬅ Previous Topic
Number of Provinces in an Undirected GraphNext Topic ⮕
Rotten Oranges Problem - BFS in MatrixYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.