Created
May 25, 2021 03:36
-
-
Save joshparkerj/0560b9adb5990c9e9ca7da3ebbac038c to your computer and use it in GitHub Desktop.
Number of Islands
This file contains 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
/** | |
* @param {character[][]} grid | |
* @return {number} | |
*/ | |
var numIslands = function(grid) { | |
var visited = grid.map(array => array.map(e => false)); | |
var counter = 0; | |
var visit = function(i, j) { | |
visited[i][j] = true; | |
if (i > 0 && grid[i - 1][j] === '1' && !visited[i - 1][j]) { | |
visit(i - 1, j); | |
} | |
if (i < grid.length - 1 && grid[i + 1][j] === '1' && !visited[i + 1][j]) { | |
visit(i + 1, j); | |
} | |
if (j > 0 && grid[i][j - 1] && grid[i][j - 1] === '1' && !visited[i][j - 1]) { | |
visit(i, j - 1); | |
} | |
if (j < grid[i].length - 1 && grid[i][j + 1] === '1' && !visited[i][j + 1]) { | |
visit(i, j + 1); | |
} | |
} | |
for (var i = 0; i < grid.length; i++) { | |
for (var j = 0; j < grid[i].length; j++) { | |
if (grid[i][j] === '1' && !visited[i][j]) { | |
visit(i, j); | |
counter++; | |
} | |
} | |
} | |
return counter; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment