标签:code ber represent range str let span 多维数组 object
原文引用https://www.dazhuanlan.com/2019/08/26/5d62fb8538067/
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.
Answer: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:
给出一个多维数组,为1的元素是岛屿,求岛屿的周长。
依次判断。
代码实现(java):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
class {
public int islandPerimeter(int[][] grid) {
int w = grid.length;
int h = grid[0].length;
int res = 0;
for (int i = 0; i < w; i++){
for (int j = 0; j < h; j++){
if(grid[i][j] == 1){
if(i == 0 || grid[i - 1][j] == 0)
res++;
if(i == w - 1 || grid[i + 1][j] == 0)
res++;
if(j == 0 || grid[i][j - 1] == 0)
res++;
if(j == h - 1 || grid[i][j + 1] == 0)
res++;
}
}
}
return res;
}
}
|
python实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Solution(object):
def islandPerimeter(self, grid):
w = len(grid)
h = len(grid[0])
res = 0
for i in range(w):
for j in range(h):
if grid[i][j] == 1:
if j-1 < 0 or grid[i][j-1] == 0:
res += 1
if j+1 >= h or grid[i][j+1] == 0:
res += 1
if i-1 < 0 or grid[i-1][j] == 0:
res += 1
if i+1 >= w or grid[i+1][j] == 0:
res += 1
return res
|
标签:code ber represent range str let span 多维数组 object
原文地址:https://www.cnblogs.com/petewell/p/11410452.html