You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
Example:
Input:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:
代码
Approach #1 Better Counting
Time: O(mn) Space: O(1)
classSolution {publicintislandPerimeter(int[][] grid) {int rows =grid.length;int cols = grid[0].length;int result =0;for (int r =0; r < rows; r++) {for (int c =0; c < cols; c++) {if (grid[r][c] ==1) { result +=4;if (r >0&& grid[r-1][c] ==1) { result -=2; }if (c >0&& grid[r][c-1] ==1) { result -=2; } } } }return result; }}
Approach #2
loop over the matrix and count the number of islands;
if the current dot is an island, count if it has any right neighbour or down neighbour;
the result is islands 4 - neighbours 2
classSolution {publicintislandPerimeter(int[][] grid) {int islands =0, neighbours =0;int R =grid.length;int C = grid[0].length;for (int i =0; i < R; i++) {for (int j =0; j < C; j++) {if (grid[i][j] ==1) { island++;if (i < R -1&& grid[i +1][j] ==1) neighbours++;if (j < C -1&& grid[i][j +1] ==1) neighbours++; } } }return islands *4- neighbours *2; }}
Approach #3 Simple Counting
publicclassSolution {publicintislandPerimeter(int[][] grid) {int rows =grid.length;int cols = grid[0].length;int up, down, left, right;int result =0;for (int r =0; r < rows; r++) {for (int c =0; c < cols; c++) {if (grid[r][c] ==1) {if (r ==0) { up =0; }else { up = grid[r-1][c]; }if (c ==0) { left =0; } else { left = grid[r][c-1]; }if (r == rows-1) { down =0; }else { down = grid[r+1][c]; }if (c == cols-1) { right =0; }else { right = grid[r][c+1]; } result +=4-(up+left+right+down); } } }return result; }}