Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save joshparkerj/0560b9adb5990c9e9ca7da3ebbac038c to your computer and use it in GitHub Desktop.
Save joshparkerj/0560b9adb5990c9e9ca7da3ebbac038c to your computer and use it in GitHub Desktop.
Number of Islands
/**
* @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