标签:表示 i++ 构造 problem href ble 二维 otto ++
题目大意:给出一个二维数组1表示陆地0表示海,求陆地的周长
思路:
重新构造一张地图grid2即一个二维数组,比原数组大一圈,即长宽都大2
一个点在原地图坐标是(i,j),那么在重新构造的坐标就是(i+1,j+1)
遍历原地图,如果一是陆地,就遍历这个点的周围是否是海,如果是海线周长就加1
Java实现:
public int islandPerimeter(int[][] grid) {
int total = 0;
int[][] grid2 = new int[grid.length+2][grid[0].length+2];
for (int i=0; i<grid.length; i++) {
for (int j=0; j<grid[0].length; j++) {
if (grid[i][j] == 1) {
grid2[i+1][j+1] = 1;
}
}
}
for (int i=0; i<grid.length; i++) {
for (int j=0; j<grid[i].length; j++) {
int x = i+1;
int y = j+1;
if (grid2[x][y] == 0) continue;
// left
total += grid2[x-1][y]==1?0:1;
// right
total += grid2[x+1][y]==1?0:1;
// top
total += grid2[x][y-1]==1?0:1;
// bottom
total += grid2[x][y+1]==1?0:1;
}
}
return total;
}
463. Island Perimeter - LeetCode
标签:表示 i++ 构造 problem href ble 二维 otto ++
原文地址:https://www.cnblogs.com/okokabcd/p/9251638.html