Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
- Example 1:
- 11110
- 11010
- 11000
- 00000
- Answer: 1
- Example 2:
- 11000
- 11000
- 00100
- 00011
- Answer: 3
- */
- /**
- * @param {character[][]} grid
- * @return {number}
- */
- var numIslands = function(grid) {
- var arr = grid;
- var count = 0;
- for(var x = 0; x < arr.length; x++) {
- for (var y = 0; y < arr[0].length; y++) {
- if(arr[x][y] === '1') {
- arr[x][y] = '0';
- count++;
- helper(arr, x + 1, y);
- helper(arr, x, y + 1);
- helper(arr, x - 1, y);
- helper(arr, x, y -1 );
- }
- }
- }
- return count;
- };
- function helper(arr, x, y) {
- if(x > arr.length - 1 || y > arr[0].length - 1) {
- return;
- }
- if(x < 0 || y < 0) {
- return;
- }
- if(arr[x][y] === '0' ) {
- return;
- }
- if(arr[x][y] === '1') {
- arr[x][y] = '0';
- }
- helper(arr, x + 1, y);
- helper(arr, x, y + 1);
- helper(arr, x - 1, y);
- helper(arr, x, y -1 );
- }
Add Comment
Please, Sign In to add comment