# Java solution DFS, no math tricky

• The idea is for a perimeter, one side is land, the other side must be water or boundary of matrix.

``````  public int islandPerimeter(int[][] grid) {
if(grid.length == 0) return 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] == 1){
return helper(grid, i, j);
}
}
}
return 0;
}

private int helper(int[][] grid, int i, int j){
grid[i][j] = -1;
int count = 0;

if(i - 1 < 0 || grid[i - 1][j] == 0) count++;
else if(grid[i - 1][j] == 1) count += helper(grid, i - 1, j);

if(i + 1 >= grid.length || grid[i + 1][j] == 0) count++;
else if(grid[i + 1][j] == 1) count += helper(grid, i + 1, j);

if(j - 1 < 0 || grid[i][j - 1] == 0) count++;
else if(grid[i][j - 1] == 1) count += helper(grid, i, j - 1);

if(j + 1 >= grid[0].length || grid[i][j + 1] == 0) count++;
else if(grid[i][j + 1] == 1) count += helper(grid, i, j + 1);

return count;
}``````

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