出去走了一下午,被拉去做苦力,累死了,刚回来。
这道题应该是裸的DFS或者BFS吧。let me try 好像还没练过DFS
class Solution {
public int maxIsland( int[][] grid , int x , int y , int row , int column ){
if( x >= 0 && x < row && y >= 0 && y < column && grid[ x ][ y ] == 1 ){
grid[ x ][ y ] = 0;//不懂这里为啥要置为0,说是为了避免重复访问?
return 1 + maxIsland( grid , x - 1 , y , row , column ) + maxIsland( grid , x + 1 , y , row , column ) + maxIsland( grid , x , y + 1 , row , column ) + maxIsland( grid , x , y - 1 , row , column );
}
return 0;
}
public int maxAreaOfIsland(int[][] grid) {
int row = grid.length;
int column = grid[ 0 ].length;
int maxArea = 0;
for( int x = 0 ; x < row ; x ++ ){
for( int y = 0 ; y < column ; y ++ ){
if( grid[ x ][ y ] == 1 )
maxArea = Math.max( maxArea , maxIsland( grid , x , y , row , column ));
}
}
return maxArea;
}
}
class Solution {
public int maxArea( int[][] grid , int i , int j , int row , int column , int area ){
if( i < 0 || i >= row || j < 0 || j >= column || grid[ i ][ j ] == 0 )
return area;
else{
area ++;
grid[ i ][ j ] = 0;
area = maxArea( grid , i - 1 , j , row , column , area );
area = maxArea( grid , i + 1 , j , row , column , area );
area = maxArea( grid , i , j - 1 , row , column , area );
area = maxArea( grid , i , j + 1 , row , column , area );
return area;
}
}
public int maxAreaOfIsland(int[][] grid) {
int row = grid.length;
int column = grid[ 0 ].length;
int maxArea = 0;
for( int i = 0 ; i < row ; i ++ ){
for( int j = 0 ; j < column ; j ++ ){
int area = 0;
if( grid[ i ][ j ] == 1 )
maxArea = Math.max( maxArea( grid , i , j , row , column , area ), maxArea );
}
}
return maxArea;
}
}