C++ my solution by counting borders


  • 1
    S
        int islandPerimeter(vector<vector<int>>& grid) {
        if(grid.empty()) {return 0;}
        int m = grid.size(), n = grid[0].size(), cnt = 0;
        
        for(int r = 0; r != m; ++r)
            for(int c = 0; c != n; ++c)
            {
                if(grid[r][c] == 1 && (r == 0     || grid[r-1][c] != 1)) cnt += 1; //up
                if(grid[r][c] == 1 && (r == m - 1 || grid[r+1][c] != 1)) cnt += 1; //down
                if(grid[r][c] == 1 && (c == 0     || grid[r][c-1] != 1)) cnt += 1; //left
                if(grid[r][c] == 1 && (c == n - 1 || grid[r][c+1] != 1)) cnt += 1; //right 
            }
        return cnt;
    }

Log in to reply
 

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