class Solution {//这个代码是错的 下面是对的
public:
int islandPerimeter(vector<vector<int>>& grid) {
int number1count = 0;
stack<int>S;
for (int i = 0; i < grid[0].size(); i++)//这里有错
{
for (int j = 0; j < grid.size(); j++)
{
if (grid[i][j] == 1)
{
number1count++;
int around = 0;
if (i + 1 < grid[0].size() )
{
if(grid[i + 1][j] == 1)
{
around++;
}
}
if (j + 1 < grid.size()) {
if(grid[i][j + 1] == 1)
around++;
}
if (i - 1 >= 0 )
{if(grid[i - 1][j] == 1)
around++;
}
if (j - 1 >=0 )
{
if( grid[i][j - 1] == 1)
around++;
}
S.push(around);
}
}
}
int aroundsize = number1count * 4;
int sum = 0;
while (!S.empty())
{
sum+= S.top();
S.pop();
}
return aroundsize-sum;
}
};
(注这个代码是错的)
grid[i][j]中的i是grid的大小
此时
优化
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int aroundsize = 0;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
if (grid[i][j] == 1)
{
aroundsize+=4;
int around = 0;
if (i + 1 < grid.size() && grid[i + 1][j] == 1)
{
aroundsize-=2;
}
if (j + 1 < grid[0].size() && grid[i][j + 1] == 1) {
aroundsize-=2;
}
}
}
}
return aroundsize;
}
};
这个和卫兵问题好像,其实不用遍历上下左右,只需按照顺序遍历右上或左下即可