C++ solution using "edge detector"


  • 0
    B

    If we consider the matrix as a binary image, the problem is a simple application of edge detector: we just have to evaluate the discrete gradient at each pixel and sum them up. While boundaries can be handled easily by extending image by zeros by 1 pixel in each direction, it is also possible to avoid extra space by paying special attention to those boundary pixels.

    class Solution {
    public:
        int islandPerimeter(vector<vector<int>>& grid) {
            int n = grid.size(), m = grid[0].size();
            int grad = 0;
            for(size_t i = 0; i < n; i++){
                for(size_t j = 0; j < m; j++){
                    grad += (i == 0 ? grid[i][j] : abs(grid[i][j] - grid[i-1][j]));
                    grad += (i == n - 1 ? grid[i][j] : 0);
                    grad += (j == 0 ? grid[i][j] : abs(grid[i][j] - grid[i][j-1]));
                    grad += (j == m - 1 ? grid[i][j] : 0);
                }
            }
            return grad;
        }
    };
    
    NOV16

Log in to reply
 

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