Island Perimeter

https://leetcode.com/problems/island-perimeter/

 class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int m=grid.size();//row
        int n=grid[0].size();//col
        int ans=0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(grid[i][j]==1){
                    ans+=4;//if 1 in matrix perimeter 4
                    if(i<m-1 && grid[i+1][j]) ans--;//if neighbours are 1 we reduce ans
                    if(j<n-1 && grid[i][j+1]) ans--;
                    if(i && grid[i-1][j]) ans--;
                    if(j && grid[i][j-1]) ans--;
                }
                
            }
        }
        return ans;
    }
};

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!