Simplest Way to Count Perimeter


  • 0
    S

    Since there is only one island in grid, so every cell marked as '1' is connected to other cells marked as '1'. To calculate the perimeter, we only need to see if a "1" grid's up/down/left/right has water or not.

    class Solution {
    public:
        
        int islandPerimeter(vector<vector<int>>& grid) {
            int perimeter = 0;
            for (int i = 0; i < grid.size(); i++) {
                for (int j = 0; j < grid[0].size(); j++) {
                    if (grid[i][j] == 0) continue;
                    if (i - 1 < 0 || grid[i-1][j] == 0) perimeter++;
                    if (i + 1 >= grid.size() || grid[i+1][j] == 0) perimeter++;
                    if (j - 1 < 0 || grid[i][j-1] == 0) perimeter++;
                    if (j + 1 >= grid[0].size() || grid[i][j+1] == 0) perimeter++;
                }
            }
            return perimeter;
        }
    };
    

  • 0
    S
    This post is deleted!

Log in to reply
 

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