跳转至

695.Max Area of Island

Tags: Medium Array Depth-first Search

Links: https://leetcode.com/problems/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.


class Solution {
    int res = 0;
    int direction[4][2] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
    int m, n;

public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        m = grid.size(); n = grid[0].size();
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                int cnt = 0;
                if (grid[i][j]) {
                    DFS(i, j, cnt, grid);
                    res = max(res, cnt);
                }
            }
        }

        return res;
    }

    void DFS(int row, int col, int & cnt, vector<vector<int>>& grid)
    {
        grid[row][col] = 0;
        ++cnt;

        for (int i = 0; i < 4; ++i) {
            int nextRow = row + direction[i][0];
            int nextCol = col + direction[i][1];
            if (0 <= nextRow && nextRow < m && 0 <= nextCol && nextCol < n 
                && grid[nextRow][nextCol]) {
                DFS(nextRow, nextCol, cnt, grid);
            }
        }
    }
};

就是lake counting问题的变形。类似的还有200