Simple C++ solution


  • 0
    H

    A land without neighbor lands would have 4 edges contributing to perimeter. With each neighbor land 1 edge gets cancelled...

    int islandPerimeter(vector<vector<int>>& grid) { // 132 ms, O(m*n)
    	int res = 0;
    	for (int i = 0; i < grid.size(); i++) {
    		for (int j = 0; j < grid[0].size(); j++) {
    			if (grid[i][j] == 1) {
    				int neighbors = 0;
    				if (i - 1 >= 0) 
    					neighbors += grid[i - 1][j];
    				if (i + 1 < grid.size()) 
    					neighbors += grid[i + 1][j];
    				if (j - 1 >= 0) 
    					neighbors += grid[i][j - 1];
    				if (j + 1 < grid[0].size()) 
    					neighbors += grid[i][j + 1];
    				res += 4 - neighbors;
    			}
    		}
    	}
    	return res;
    }
    

Log in to reply
 

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