C++ Solution beats 99%


  • 0
    A

    The basic premise is that every perimeter unit is a water-land boundary. So simply check for these in the 4 cardinal directions.
    Note that even at matrix boundaries( edge-cases ) , there is a boundary at the outer edge.

    class Solution {
    public:
        int islandPerimeter(vector<vector<int>>& 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 )
                    {
                        if(i == 0 || grid[i-1][j] == 0 ) count++ ; 
                        if(i == grid.size() - 1  || grid[i+1][j] == 0 ) count++ ; 
                        if(j == 0 || grid[i][j-1] == 0 ) count++ ; 
                        if(j == grid[0].size()-1 || grid[i][j+1] == 0 ) count++ ; 
                    }
                }
                return count ; 
        }
    };
    

Log in to reply
 

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