zoukankan      html  css  js  c++  java
  • leetcode 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.
    

    没啥好说的,直接dfs就行了....做过n遍这个题了....

    class Solution {
    public:
        int dir[4][2] = {1,0,0,1,0,-1,-1,0};
        int n, m, ans, cnt;
        map<pair<int,int>, int>mp;
        void dfs(int x, int y, vector<vector<int>>& grid) {
            mp[{x, y}] = 1;
            ++cnt;
            for (int i = 0; i < 4; ++i) {
                int nx = x + dir[i][0];
                int ny = y + dir[i][1];
                if (nx < n && ny < m && nx >=0 && ny >= 0 && !mp[{nx,ny}] && (grid[nx][ny] == 1)) {
                    dfs(nx, ny, grid);
                }
            }
        }
        int maxAreaOfIsland(vector<vector<int>>& grid) {
            n = grid.size();
            m = grid[0].size();
            mp.clear();
            ans = 0;
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < m; ++j) {
                    if (mp[{i,j}] == 0 && grid[i][j] == 1) {
                        cnt = 0;
                        dfs(i, j, grid);
                        ans = max(ans, cnt);
                    }
                }
            }
            return ans;
        }
    };
    /*
    1 1 0 0 0
    1 1 0 0 0
    0 0 0 1 1
    0 0 0 1 1
    */
    

    111x
    欢迎关注:)

  • 相关阅读:
    12.Docker网络类型
    博客迁移
    java注解
    IO多路复用技术(multiplexing)
    Java 中extends与implements使用方法
    初识autoconf
    初识swoole
    简单配置nginx使之支持pathinfo
    vue-cli 脚手架 安装过程
    PHP阻止页面后退如何用PHP实现禁用浏览器的后退,使后退的页面失效或链接到别的地方?使用php禁止浏览器缓存?
  • 原文地址:https://www.cnblogs.com/pk28/p/7648318.html
Copyright © 2011-2022 走看看