I'm slightly confused how Java works, I know the following to be true:
public static void main(String[] args) {
int c=0;
changeC(c);
System.out.println(c); // 0
}
public static void changeC(int c) {
c++;
}
We know c
outputs 0
because the changeC
method does not change the original c
Now I'm looking at a solution on Leetcode, and it seems to following a similar concept.
Here is the code:
public int numIslands(char[][] grid) {
int count=0;
for(int i=0;i<grid.length;i++)
for(int j=0;j<grid[0].length;j++){
if(grid[i][j]=='1'){
dfsFill(grid,i,j);
count++;
}
}
return count;
}
private void dfsFill(char[][] grid,int i, int j){
if(i>=0 && j>=0 && i<grid.length && j<grid[0].length&&grid[i][j]=='1'){
grid[i][j]='0';
dfsFill(grid, i + 1, j);
dfsFill(grid, i - 1, j);
dfsFill(grid, i, j + 1);
dfsFill(grid, i, j - 1);
}
}
In this case, the grid is passed to the void function dfsFills()
. Yet, whatever dfsFill()
does to grid
, the grid
in the numIslands()
function is also updated.
Why does this act differently than my first example? Is one pass by reference and the other pass by value?