Created
June 12, 2020 04:40
-
-
Save techsin/9e289c1564f56765567cd95ff158b732 to your computer and use it in GitHub Desktop.
find islands leetcode
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
var numIslands = function(grid) { | |
let islands = 0; | |
for (let i = 0; i < grid.length; i++) { | |
for (let j = 0; j < grid[i].length; j++) { | |
if (grid[i][j] == 1) { | |
markRecur(i, j, grid); | |
islands++; | |
} | |
} | |
} | |
return islands; | |
}; | |
function markRecur(x, y, grid) { | |
grid[Number(x)][Number(y)] = 'x'; | |
if (grid[x-1] && grid[x-1][y] == 1) markRecur(x-1, y, grid); | |
if (grid[x+1] && grid[x+1][y] == 1) markRecur(x+1, y, grid); | |
if (grid[x][y+1] && grid[x][y+1] == 1) markRecur(x, y+1, grid); | |
if (grid[x][y-1] && grid[x][y-1] == 1) markRecur(x, y-1, grid); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://leetcode.com/problems/number-of-islands/