Count cells and shared sides
Time O(rows × cols) Space O(1)perimeter = 4 × land − 2 × (land cells with land below + land cells with land to the right).
grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]Step 1/37 land cells: 7 × 4 = 28 sides.
class Solution {
public int islandPerimeter(int[][] grid) {
int land = 0, shared = 0;
for (int r = 0; r < grid.length; r++)
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == 0) continue;
land++;
if (r + 1 < grid.length && grid[r + 1][c] == 1) shared++;
if (c + 1 < grid[0].length && grid[r][c + 1] == 1) shared++;
}
return 4 * land - 2 * shared;
}
}Verdict: No DFS needed.