C++ clear solution O(MN)


  • 1
    S
    class Solution {
    public:
        int islandPerimeter(vector<vector<int>>& grid) {
            int count = 0;
            int xSize = grid.size();
            int ySize = grid[0].size();
            for(int x = 0 ; x < xSize ; x++)
            {
                for(int y = 0 ; y < ySize ; y++)
                {
                    if(grid[x][y] == 1)
                    {
                        if(x-1 < 0 || grid[x-1][y] == 0)
                            count++;
                        if(x+1 > xSize-1 || grid[x+1][y] == 0)
                            count++;
                        if(y-1 < 0 || grid[x][y-1] == 0)
                            count++;
                        if(y+1 > ySize-1 || grid[x][y+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.