白板
有时候看到题时,可能会一脸懵逼,那么不妨现将题目的描述画到白板上,然后在白板上进行分析,想到答案的速度会比单纯在脑海中进行思考要快很多。
力扣463 岛屿的周长
463. 岛屿的周长
给定一个包含 0 和 1 的二维网格地图,其中 1 表示陆地 0 表示水域。
网格中的格子水平和垂直方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。
岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。
示例 :
输入:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
输出: 16
解释: 它的周长是下面图片中的 16 个黄色的边:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/island-perimeter
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int row = grid.size();
int col = grid[0].size();
int ret = 0;
for(int i = 0; i < row; i++)
{
int tmp = 0;
for(int j = 0; j < col; j++)
{
if(grid[i][j] == 1)
{
if( i-1 < 0)
tmp++;
else
{
if(grid[i-1][j] == 0)
tmp++;
}
if(i+1 >= row)
tmp++;
else
{
if(grid[i+1][j] == 0)
tmp++;
}
if(j-1 < 0)
tmp++;
else
{
if(grid[i][j-1] == 0)
tmp++;
}
if(j+1 >= col)
tmp++;
else
{
if(grid[i][j+1] == 0)
tmp++;
}
}
}
ret += tmp;
}
return ret;
}
};
在讨论区中看到了一个通过计算其“邻居”是否为1的方法,十分的巧妙
//1. loop over the matrix and count the number of islands;
//2. if the current dot is an island, count if it has any right neighbour or down neighbour;
//3. the result is islands * 4 - neighbours * 2
public class Solution {
public int islandPerimeter(int[][] grid) {
int islands = 0, neighbours = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 1) {
islands++; // count islands
if (i < grid.length - 1 && grid[i + 1][j] == 1) neighbours++; // count down neighbours
if (j < grid[i].length - 1 && grid[i][j + 1] == 1) neighbours++; // count right neighbours
}
}
}
return islands * 4 - neighbours * 2;
}
}