# My Java solution with explanation

• Hi All,
For this problem, we can see that the total number of edges is related to the '0' element, i.e., if left grid, upper grid, right grid or down grid of '1' is '0', then the count of total edges plus 1 for every grid '1'. Also, if the location of element '1' is at the side of the matrix, the count also plus 1. Then we traverse the matrix and add them all. Here is the code. Hope it helps.

``````public int islandPerimeter(int[][] grid) {
if(grid.length == 0){
return 0;
}

int res = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
res = res + check(grid, i, j);
}
}

return res;
}

private int check(int[][] grid, int i, int j){
int sum = 0;
if(grid[i][j] == 1){
if(i == 0){
sum++;
}

if(i == grid.length - 1){
sum++;
}

if(j == 0){
sum++;
}

if(j == grid[0].length - 1){
sum++;
}

if(i + 1 < grid.length){
if(grid[i + 1][j] == 0){
sum++;
}
}

if(i - 1 >= 0){
if(grid[i - 1][j] == 0){
sum++;
}
}

if(j + 1 < grid[0].length){
if(grid[i][j + 1] == 0){
sum++;
}
}

if(j - 1 >= 0){
if(grid[i][j - 1] == 0){
sum++;
}
}
}

return sum;
}``````

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