My very easily understood c++ solution 6ms


  • 0
    The main idea is to iterate through every point in the grid: if it is '1' , then replace every '1' adjacent to that point with another different char '2', and count++.
    class Solution {
    public:
        int numIslands(vector<vector<char>>& grid) {
            int count = 0;
            for(int i = 0; i < grid.size(); i++){
                for(int j = 0; j < grid[0].size(); j++){
                    if(grid[i][j] == '1'){
                        helper(i, j, grid);
                        count++;
                    }
                }
            }
            return count;
        }
        void helper(int i, int j, vector<vector<char>>& grid){
            if(i < 0 || i >= grid.size()){return;}
            if(j < 0 || j >= grid[0].size()){return;}
            if(grid[i][j] != '1'){return;}
            grid[i][j] = '2';
            helper(i + 1, j, grid);
            helper(i - 1, j, grid);
            helper(i, j + 1, grid);
            helper(i, j - 1, grid);
        }
    };

Log in to reply
 

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