Created
April 8, 2026 15:23
-
-
Save petergi/d0e28e45fb23c505a4c402ac078b7523 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function traverse(matrix) { | |
| const DIRECTIONS = [[0, 1], [0, -1], [1, 0], [-1, 0]]; | |
| const rows = matrix.length, cols = matrix[0].length; | |
| const visited = matrix.map(row => Array(row.length).fill(false)); | |
| function dfs(i, j) { | |
| if (visited[i][j]) { | |
| return; | |
| } | |
| visited[i][j] = true; | |
| DIRECTIONS.forEach(dir => { | |
| 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); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment