You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
759 B
36 lines
759 B
5 years ago
|
function traverse(matrix) {
|
||
2 years ago
|
const DIRECTIONS = [
|
||
|
[0, 1],
|
||
|
[0, -1],
|
||
|
[1, 0],
|
||
|
[-1, 0],
|
||
|
];
|
||
5 years ago
|
const rows = matrix.length;
|
||
|
const cols = matrix[0].length;
|
||
2 years ago
|
const visited = matrix.map((row) => Array(row.length).fill(false));
|
||
5 years ago
|
function dfs(i, j) {
|
||
|
if (visited[i][j]) {
|
||
|
return;
|
||
|
}
|
||
|
visited[i][j] = true;
|
||
2 years ago
|
DIRECTIONS.forEach((dir) => {
|
||
5 years ago
|
const row = i + dir[0],
|
||
|
col = j + dir[1];
|
||
|
// Boundary check.
|
||
|
if (row < 0 || row >= rows || col < 0 || col >= cols) {
|
||
|
return;
|
||
|
}
|
||
|
// Valid neighbor check.
|
||
|
if (matrix[row][col] !== 1) {
|
||
|
return;
|
||
|
}
|
||
|
dfs(row, col);
|
||
|
});
|
||
|
}
|
||
|
for (let i = 0; i < rows; i++) {
|
||
|
for (let j = 0; j < cols; j++) {
|
||
|
dfs(i, j);
|
||
|
}
|
||
|
}
|
||
|
}
|