C++ with explanation. The total time complexity is O(mn) and space complexity is O(1).


  • 0
    L

    For each grid cell with value 1, check its left cell and up cell, if its neighbors are not 1, then increasing the corresponding rows/cols by 1.

    class Solution {
    public:
        int islandPerimeter(vector<vector<int>>& grid) {
            int rows=0,cols=0;
            for(int i=0;i<grid.size();i++){
                for(int j=0;j<grid[0].size();j++){
                    if(grid[i][j] == 1 && (j == 0 || grid[i][j-1] != 1))  rows++;
                    if(grid[i][j] == 1 && (i == 0 || grid[i-1][j] != 1))  cols++;
                }
            }
            return (rows+cols)*2;
        }
    };
    

Log in to reply
 

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