So today I was doing some leetcode problems, and I came across this one: number of closed islands.
This is my initial solution:
class Solution {
public int closedIsland(int[][] grid) {
int ans = 0;
for(int i=0;i<grid.length; i++){
for(int j=0; j<grid[0].length;j++){
if(grid[i][j]==0 && visit(grid, i, j)){
ans++;
}
}
}
return ans;
}
public boolean visit(int[][] grid, int row, int col){
if(row>=grid.length || col>=grid[0].length || row<0 || col<0) return false;
if(grid[row][col]==1 || grid[row][col]==-1) return true;
grid[row][col] = -1;
return visit(grid, row+1, col)&
visit(grid, row-1, col)&
visit(grid, row, col+1)&
visit(grid, row, col-1);
}
}
And it passed all the test cases. However, when I replaced &
with &&
in the return statement in visit(...)
, the new solution failed some cases.