LC695 Max Area of Island
class Solution {
private int count = 0;
public int maxAreaOfIsland(int[][] grid) {
if(grid == null || grid.length == 0) return 0;
int res = 0;
int row = grid.length;
int col = grid[0].length;
for(int i = 0; i<row; i++){
for(int j = 0; j<col; j++){
if(grid[i][j] == 1){
helper(grid, i, j); //helper indicates the area expand from (i,j): int
res = Math.max(res, count);// and I believe the mainly mistake here is pass by value and pass by reference, in other words, temp is not changed at all
count = 0;
}
}
}
return res;
}
private int helper(int[][] grid, int i, int j){
if(grid[i][j] == 1){
grid[i][j] = 0;
count++;
if(i>0 && grid[i-1][j] == 1){ //only goes one way or maybe more way will decide whether to use if/if/if or if/else if/else if
return helper(grid, i - 1, j);
}
if(i<grid.length - 1 && grid[i+1][j] == 1){
return helper(grid, i + 1, j);
}
if(j>0 && grid[i][j-1] == 1){
return helper(grid, i, j - 1);
}
if(j<grid[0].length - 1 && grid[i][j+1] == 1){
return helper(grid, i, j + 1);
}
}
return 0;
}
}
原因:不应该return helper()应该直接Helper()
class Solution {
private int count = 0;
public int maxAreaOfIsland(int[][] grid) {
if(grid == null || grid.length == 0) return 0;
int res = 0;
int row = grid.length;
int col = grid[0].length;
for(int i = 0; i<row; i++){
for(int j = 0; j<col; j++){
if(grid[i][j] == 1){
helper(grid, i, j); //helper indicates the area expand from (i,j): int
res = Math.max(res, count);// and I believe the mainly mistake here is pass by value and pass by reference, in other words, temp is not changed at all
count = 0;
}
}
}
return res;
}
private void helper(int[][] grid, int i, int j){
if(grid[i][j] == 1){
grid[i][j] = 0;
count++;
if(i>0 && grid[i-1][j] == 1){ //only goes one way or maybe more way will decide whether to use if/if/if or if/else if/else if
helper(grid, i - 1, j);
}
if(i<grid.length - 1 && grid[i+1][j] == 1){
helper(grid, i + 1, j);
}
if(j>0 && grid[i][j-1] == 1){
helper(grid, i, j - 1);
}
if(j<grid[0].length - 1 && grid[i][j+1] == 1){
helper(grid, i, j + 1);
}
}
return;
}
}
为什么?因为我们目的是往下走就完了(因为count是个全局变量)就往后走 一直到到最后触底return.