Created
November 9, 2017 17:19
-
-
Save hoanbka/3f407ccef9c7751eac716d2aaf8dcffe to your computer and use it in GitHub Desktop.
number-of-islands.js
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
/** | |
* Created by Hoan Nguyen on 11/9/2017. | |
*/ | |
/** | |
* @param {character[][]} grid | |
* @return {number} | |
*/ | |
var n; | |
var m; | |
var numIslands = function(grid) { | |
var count = 0; | |
n = grid.length; | |
if (n == 0) return 0; | |
m = grid[0].length; | |
for (var i = 0; i < n; i++) { | |
for (var j = 0; j < m; j++) | |
if (grid[i][j] == '1') { | |
DFS(grid, i, j); | |
++count; | |
} | |
} | |
return count; | |
}; | |
function DFS(grid, i, j) { | |
if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] != '1') return; | |
grid[i][j] = '0'; | |
DFS(grid, i + 1, j); | |
DFS(grid, i - 1, j); | |
DFS(grid, i, j + 1); | |
DFS(grid, i, j - 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment