Leetcode 695. Max Area of Island

来源:互联网 发布:java面试吹牛 编辑:程序博客网 时间:2024/06/05 01:10

题目:
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.


分析:
这道题本质上是要求我们求一个矩阵中所有邻接且值为1的点的最大数量,很直接的想法就是去遍历每一个点,判断其是否为1,如果是,则深度优先搜索其上下左右邻接点是否为1,如果是则继续深搜并使总面积加1,如果不是则终止递归,表示陆地已到尽头。
关键点:搜索时必须保证点没有在矩阵范围外,并且时仍没被访问过的点,避免重复循环访问。


具体做法:

  • step1:对矩阵的每一个点进行遍历,并判断其是否已被访问或是否值为1.

  • step2:如果此点未曾被访问,且值为1,则开始DFS其周围点,每次遍历到一个新的点,将它的visited值设为true,这样下次就不用重复访问了。

  • step3:递归返回上下左右点的DFS值+1,与当前最大面积作比较,取大的一个,返回最终的最大面积,总时间复杂度为O(n^2)

代码:

#include <iostream>#include <vector>#include <algorithm>using namespace std;/*深度优先搜索所有相邻且值为1的点*/int DFS(int i, int j, int row, int col, vector<vector<bool>>& isVisited,             vector<vector<int>>& grid) {    if (i >= 0 && i <= row - 1 && j >= 0 && j <= col - 1 && !isVisited[i][j] &&                grid[i][j]) {   //所搜索的点必须满足不越界、没有被访问过、值为1        isVisited[i][j] = true;     //访问过的点visited值设为true        return DFS(i + 1, j, row, col, isVisited, grid) + DFS(i - 1, j, row, col, isVisited, grid) +             DFS(i, j + 1, row, col, isVisited, grid) + DFS(i, j - 1, row, col, isVisited, grid) + 1;    }       //分别递归搜索上、下、左、右的点    else return 0;  //此点越界或已访问过或值为0}class Solution {public:    int maxAreaOfIsland(vector<vector<int>>& grid) {        int row = grid.size();        if (row == 0) return 0;     //处理空的grid        int col = grid[0].size();        int max_area = 0;        vector<vector<bool>> isVisited(row, vector<bool>(col, false));        for (int i = 0; i < row; i++) {            for (int j = 0; j < col; j++) {                if (!isVisited[i][j] && grid[i][j]) {                    /*在当前max_area和DFS后得到的总面积取大的那个*/                    max_area = max(max_area, DFS(i, j, row, col, isVisited, grid));                }            }        }        return max_area;    //返回最大的总面积    }};