C++ Simple Solution


  • 0

    Explanation:
    every land have 4 edges,
    remove an edge when you find a neighbor

    class Solution {
    public:
        int islandPerimeter(vector<vector<int>>& grid) {
            int m = grid.size(), n = m ? grid[0].size() : 0, res = 0;
            if (!n)
                return 0;
            vector<pair<int, int>> nei = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
            for (int i = 0; i < m; i++)
                for (int j = 0; j < n; j++) {
                    if (grid[i][j]) {
                        res += 4;
                        for (auto k : nei) {
                            int r = k.first + i, c = k.second + j;
                            if (r >= 0 && r < m && c >= 0 && c < n && grid[r][c])
                                res--;
                        }
                    }
                }
            return res;
        }
    };
    

Log in to reply
 

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