JavaScript Solution Beats 97%


  • 0
    /**
     * @param {character[][]} grid
     * @return {number}
     */
    var numIslands = function(grid) {
        if (grid.length === 0) {
            return 0;
        }
        var height = grid.length;
        var width = grid[0].length;
        var sum = 0;
        var clean = function(i, j) {
            if (i >= 0 && i < height && j >= 0 && j < width && grid[i][j] == "1") {
                grid[i][j] = "0";
                clean(i + 1, j);
                clean(i - 1, j);
                clean(i, j + 1);
                clean(i, j - 1);
            }
        };
        for (var i = 0; i < height; i++) {
            for (var j = 0; j < width; j++) {
                if (grid[i][j] == "1") {
                    clean(i, j);
                    sum++;
                }
            }
        }
        return sum;
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.