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