[C++] Easy to understand.


  • 0
    M
       // Calculate each contribution(num of edges) of each cell
        int contribute(int row,int col,vector<vector<int>>& grid){
            if(grid[row][col]==0) return 0;
            int height = grid.size();
            int width = grid[0].size();
            int rs = 0;
            if(row==0 || grid[row-1][col]==0) rs++;
            if(row==height-1 || grid[row+1][col]==0) rs++;
            if(col==0 || grid[row][col-1]==0) rs++;
            if(col==width-1 || grid[row][col+1]==0) rs++;
            return rs;
        }
        int islandPerimeter(vector<vector<int>>& grid) {
            int rs = 0;
            // Visit each cell
            for(int i=0;i<grid.size();i++)
                for(int j=0;j<grid[0].size();j++)
                    rs+=contribute(i,j,grid);
            return rs;
        }
    

Log in to reply
 

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