Very simple C++ solution - beats 97%


  • 0
    A

    At each cell, this solution basically checks for water at the top, bottom, left and right. If water found, 1 unit is added to the perimeter.

    int islandPerimeter(vector<vector<int>>& grid) {
            int i=0,j=0;
            int perimeter=0;
            
            while(i< grid.size()){
                int cols= grid[i].size();
                j=0;
                while(j<cols){
                    if(grid[i][j]==1){
                        
                        //check top
                        if(i==0) perimeter += 1;
                        else if(grid[i-1][j]==0) perimeter += 1;
                        
                        //check bottom
                        if(i==(grid.size()-1)) perimeter += 1;
                        else if(grid[i+1][j]==0) perimeter += 1;
                       
                        //check left
                         if(j==0) perimeter += 1;
                         else if(grid[i][j-1]==0) perimeter += 1;
                        
                        //check right
                         if(j==cols-1) perimeter += 1;
                         else if(grid[i][j+1]==0) perimeter += 1;
                    }
                    j++;
                }
                //move to next row
                i++;
            }
            return perimeter;
        }
    

Log in to reply
 

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