Island Perimeter
You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 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", meaning the water inside 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 1:
Input: grid = [[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 above.
Example 2:
Input: grid = [[1]]
Output: 4
Example 3:
Input: grid = [[1,0]]
Output: 4
Constraints:
row == grid.length
col == grid[i].length
1 <= row, col <= 100
grid[i][j] is 0 or 1.
There is exactly one island in grid.
思路一:给定的数组,长度为 i * j,可以把数组放在一个 (i+2) * (j+2) 的新数组内,遍历新数组的时候可以省去最外层边的判断
public int islandPerimeter(int[][] grid) {
int colLen = grid.length;
int rowLen = grid[0].length;
int[][] bigGrid = new int[colLen + 2][rowLen + 2];
for (int i = 0; i < colLen; i++) {
for (int j = 0; j < rowLen; j++) {
bigGrid[i + 1][j + 1] = grid[i][j];
}
}
int result = 0;
for (int i = 1; i < bigGrid.length - 1; i++) {
for (int j = 1; j < bigGrid[0].length - 1; j++) {
result += checkCell(bigGrid, i, j);
}
}
return result;
}
private static int checkCell(int[][] grid, int i, int j) {
int result = 0;
int cell = grid[i][j];
if (cell == 1) {
if (grid[i - 1][j] == 0) {
result++;
}
if (grid[i + 1][j] == 0) {
result++;
}
if (grid[i][j - 1] == 0) {
result++;
}
if (grid[i][j + 1] == 0) {
result++;
}
}
return result;
}
思路二:看了一下题解,发现有更好的解法,关注前面遍历过得方格,如果之前有相邻方格,就-2;
if (grid[i][j] == 1) {
rsp += 4;
if (i > 0 && grid[i - 1][j] == 1) {
rsp -= 2;
}
if (j > 0 && grid[i][j - 1] == 1) {
rsp -= 2;
}
}
标签:627,bigGrid,int,++,length,grid,result,easy,leetcode
From: https://www.cnblogs.com/iyiluo/p/17023448.html