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;
    }
    };

  • 相关阅读:
    hdu-3376-Matrix Again(最小费用最大流)
    CF-164C. Machine Programming(最小费用最大流)
    splay模板
    POJ-3580-SuperMemo(splay的各种操作)
    pygame安装
    hg 证书验证失败
    hdu-3487-Play with Chain-(splay 区间翻转,切割,插入)
    jvm 重载 重写
    多线程踩坑
    hashmap时间复杂度
  • 原文地址:https://www.cnblogs.com/liangyc/p/8785889.html
Copyright © 2011-2022 走看看