c++ easy solution


  • 0
    W

    each cell potentially contribute 4 to total perimeter, if the cell is connected by another one, then we should rule out the 1 connected border because this border is not counted as outside border now

    class Solution {
    public:
    	int islandPerimeter(vector<vector<int>>& grid) {
    		int perimeter = 0;
    		for (int i = 0; i < grid.size(); ++i) {
    			for (int j = 0; j < grid[0].size(); ++j) {
    				if (grid[i][j] == 1) {
    					perimeter += 4;
    					if (i > 0 && grid[i - 1][j] == 1) perimeter -= 1;
    					if (i < grid.size() - 1 && grid[i + 1][j] == 1) perimeter -= 1;
    					if (j > 0 && grid[i][j - 1] == 1) perimeter -= 1;
    					if (j < grid[0].size() - 1 && grid[i][j + 1] == 1) perimeter -= 1;
    				}
    			}
    		}
    		return perimeter;
    	}
    };
    

Log in to reply
 

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