Stupid 232ms C++ Solution


  • 0

    Simply go over all '1' cells, check its four neighbors, if the neighbors is either a 'water'(0) or a 'wall'(out of index), there count +1 for an edge.

    class Solution {
    public:
        int islandPerimeter(vector<vector<int>>& grid) {
            int meter = 0;
            int row_size = grid.size();
            int col_size = grid[0].size();
    
            for (int row = 0; row < row_size; ++row) {
                for (int col = 0; col < col_size; ++col) {
                    int val = grid[row][col];
                    if (val == 1) {
                        // check left
                        if (col-1 < 0 || grid[row][col-1] == 0) {meter += 1;}
                        // check right
                        if (col+1 == col_size || grid[row][col+1] == 0) {meter += 1;}
                        // check up
                        if (row-1 < 0 || grid[row-1][col] == 0) {meter += 1;}
                        // check down
                        if (row+1 == row_size || grid[row+1][col] == 0) {meter += 1;}
                    }
                }
            }
            
            return meter;
            
        }
    };
    

Log in to reply
 

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