695. Max Area of Island

31 篇文章 0 订阅
27 篇文章 0 订阅

出去走了一下午,被拉去做苦力,累死了,刚回来。

 

这道题应该是裸的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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值