Skip to content

Latest commit

 

History

History
75 lines (60 loc) · 1.48 KB

8.number-of-Islands.md

File metadata and controls

75 lines (60 loc) · 1.48 KB

Number of Islands

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:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

JavaScript

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
    var newVisitingGrid = [];
    var result = 0;
    for (let i = 0; i < grid.length; ++i) {
        for (let j = 0; j < grid[i].length; ++j) {
            result += numIslandsHalper(grid, newVisitingGrid, i, j);
        }
    }

    return result;
};

var numIslandsHalper = function (grid, newVisitingGrid, x, y) {
    if (typeof(grid[x]) === 'undefined') {
        return 0;
    }
    if (typeof(newVisitingGrid[x]) === 'undefined') {
        newVisitingGrid[x] = [];
    }
    if (newVisitingGrid[x][y] === 1) {
        return 0;
    }
    if (typeof(newVisitingGrid[x]) === 'undefined') {
        newVisitingGrid[x] = [];
    }
    newVisitingGrid[x][y] = 1;


    if (grid[x][y] == 1) {
        numIslandsHalper(grid, newVisitingGrid, x + 1, y);
        numIslandsHalper(grid, newVisitingGrid, x, y + 1);
        numIslandsHalper(grid, newVisitingGrid, x - 1, y);
        numIslandsHalper(grid, newVisitingGrid, x, y - 1);

        return 1;
    }

    return 0;
}