# C++ solution with explanation

1. find how many 1 in the map. If without the consideration of surrounding cells, the total perimeter should be the total amount of 1 times 4.
2. find how many cell walls that connect with both lands. We need to deduct twice of those lines from total perimeter
``````int islandPerimeter(vector<vector<int>>& grid) {
int count=0, repeat=0;
for(int i=0;i<grid.size();i++)
{
for(int j=0; j<grid[i].size();j++)
{
if(grid[i][j]==1)
{
count ++;
if(i!=0 && grid[i-1][j] == 1) repeat++;
if(j!=0 && grid[i][j-1] == 1) repeat++;
}
}
}
return 4*count-repeat*2;
}
``````

@msg thanks for the edit

• only need two if statements

if(i!=0 && grid[i-1][j] == 1) repeat++;
if(j!=0 && grid[i][j-1] == 1) repeat++;

• @msg Thanks, you are right and make it much more concise

• This post is deleted!

• This post is deleted!

• Changing from "`i++`" to "`++i`" causes Memory Limit Exceeded. Anyone has an idea why this happens? Below are my Memory Limit Exceeded codes.

``````class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int neighbor = 0;
int island = 0;
for (int row = 0; row < grid.size(); ++row) {
for (int col = 0; col < grid[row].size(); ++col) {
if (grid[row][col] == 1) {
island++;
if (row != 0 && grid[row - 1][col] == 1) ++neighbor;
if (col != 0 && grid[row][col - 1] == 1) ++neighbor;
}
}
}
return island * 4 - 2 * neighbor;
}
};
``````

• @dcsds1 This issue was just fixed.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.