zoukankan      html  css  js  c++  java
  • 695. Max Area of Island

    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.)

    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]]
    
    Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

    Example 2:

    [[0,0,0,0,0,0,0,0]]
    Given the above grid, return 0.

    Note: The length of each dimension in the given grid does not exceed 50.

    解题思路:

    直接深搜,给每一个元素设定一个know标签,这样可以判断是否已经搜到过这个点

    class Solution {

    private:
    vector<vector<int>> know;
    int max_island=0;
    int count = 0;
    void deep(vector<vector<int>>& grid,int row,int column){

    know[row][column] = 1;
    count++;
    if(count > max_island) max_island = count;

    if(column-1>=0){
    if(know[row][column-1] == 0 && grid[row][column-1]==1 )
    deep(grid,row,column-1);
    }
    if(row-1>=0){
    if(know[row-1][column] == 0 &&grid[row-1][column]==1)
    deep(grid,row-1,column);
    }
    if(row+1<grid.size()){
    if(know[row+1][column] == 0 &&grid[row+1][column]==1)
    deep(grid,row+1,column);
    }
    if(column+1<grid[0].size()){
    if(know[row][column+1] == 0 &&grid[row][column+1]==1)
    deep(grid,row,column+1);
    }


    }

    public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {

    if(grid.size()==0) return 0;
    know = grid;
    for(int i=0;i<know.size();i++)
    for(int j=0;j<know[0].size();j++)
    know[i][j]=0;
    for(int i=0;i<grid.size();i++){

    for(int j=0;j<grid[0].size();j++){

    if(know[i][j] == 0 &&grid[i][j]==1)
    deep(grid,i,j);

    count=0;

    }



    }
    return max_island;
    }
    };

  • 相关阅读:
    ByteBuffer的mark、position、limit、flip、reset,get方法介绍ok
    java.nio.ByteBuffer的flip、rewind和compact几个方法的区分使用
    maven之一:maven安装和eclipse集成
    Java 8 函数式接口
    Lambda 表达式
    jdk8十大新的特性
    阿里巴巴73款开源产品列表,值得收藏
    【Java】java.util.Objects 工具类方法研究
    ARIMA 模型简单介绍
    python 二维数组取值
  • 原文地址:https://www.cnblogs.com/liangyc/p/8785889.html
Copyright © 2011-2022 走看看