0

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.

zxcisnoias
  • 494
  • 3
  • 19
  • 3
    The diff between `&&` and `&` is that `&&` [short-circuits](https://stackoverflow.com/questions/8759868/java-logical-operator-short-circuiting). The reason it behaves differently is because you are modifying `grid` in the `visit()` method, and when you use `&&` and it short-circuits, the modification by subsequent calls to `visit()` isn't performed. – Jesper Apr 20 '23 at 15:02

0 Answers0