1

题目详情

Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

输入一个非空的二维数组,数组由0和1组成。其中0代表水域,1表示陆地。我们需要找出整个数组所表示的地图中,面积最大的一块陆地(陆地的相连只看上下左右相邻的4个元素,如左上方这种就不算相邻!)。

Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
返回6. 注意答案并不是11, 因为陆地相连要求必须是在上下左右四个方向。
Example 2:
[[0,0,0,0,0,0,0,0]]
返回应为0.

想法

  • 我们还是要遍历数组中的每一个元素。
  • 如果数组元素值为1,则我们以这个值为起点进行深度优先搜索。
  • 遍历当前元素的相邻元素,如果有相邻元素的值为1,那么再以这个元素为起点继续搜索。
  • 为了防止重复,我们每发现一个值为1的元素,就将这个元素赋值为0,代表我们已经遍历过这个元素了。

解法

    int[][] directions = {{-1,0},{1,0},{0,-1},{0,1}}; 
    
    public int maxAreaOfIsland(int[][] grid) {
        int rows = grid.length;
        int cols = grid[0].length;
        
        int maxArea = 0;
        int currArea = 0;

        
        for(int row=0;row<rows;row++){
            for(int col=0;col<cols;col++){
                if(grid[row][col] == 1){
                    grid[row][col] = 0;
                    currArea = findArea(grid,row,col);
                    maxArea = Math.max(currArea, maxArea);
                }
            }
        }
        
        return Math.max(maxArea, currArea);
    }
    
    public int findArea(int[][] grid,int x,int y){
        int area = 1;

        for(int[] direction : directions){
            int newX = x+direction[0];
            int newY = y+direction[1];
        
            if( newX>=0 && newX < grid.length && newY >=0 && newY < grid[0].length){
                if(grid[newX][newY] == 1){
                    grid[newX][newY] = 0;
                    area += findArea(grid,newX,newY);
                    
                }
            }
        }
        
        return area;
    }
    

soleil阿璐
350 声望45 粉丝

stay real ~