695. Max Area of Island------刷过50道leetcode面试之后

刷过50道leetcode面试之后,深刻感受到,每天刷题保持状态才能在面试中写出代码。


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若四周都是水,也就是0,就称为一个岛。

求最大的岛。

不要怕,矩阵也不过是二维数组。

思路:先找到岛,然后计算岛的大小,用max_island记录目前最大的岛的大小。

问题一:如何判断是否为岛?

如果,枚举元素,遇到1,就按照上下左右的顺序查看是否有1,如果都没有1,岛的大小为1,;如果找到1,再按照顺序查看是否有1. 

这样查不全,而且还会倒回去。

discuss:用到了dfs深度搜索~

dfs算法是啥来着?

递归算法。遇到1,先置0,然后返回1+四周的dfs搜索结果。

因为置0了,所以不怕重复加。

找到1,但是四周的dfs也都加上了所以不怕查不全。


这里的矩阵相当于一个图的邻接矩阵?而题意就是去找最大连通分量?还是个有向图?不是,图的类似(2,2)的点不能为1,点跟自身不能连吧?而且矩阵行列不一定相等啊??但是图的dfs方法还是可以用的

dfs的时间复杂度:https://blog.csdn.net/wusecaiyun/article/details/49562451  o(n^2)  n为顶点数 那这里 n=max

(rows,cols)

空间复杂度 O(m) m是1的个数

空间复杂度可以改进为常数



猜你喜欢

转载自blog.csdn.net/zhangdamengcsdn/article/details/80227057
今日推荐