博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 695. Max Area of Island
阅读量:4500 次
发布时间:2019-06-08

本文共 1682 字,大约阅读时间需要 5 分钟。

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
, int>mp; void dfs(int x, int y, vector
>& 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
>& 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 01 1 0 0 00 0 0 1 10 0 0 1 1*/

111x

欢迎关注:)

转载于:https://www.cnblogs.com/pk28/p/7648318.html

你可能感兴趣的文章
sqlalchemy学习(一)
查看>>
silverlight Image Source URI : 一个反斜杠引发的血案
查看>>
Windows Phone开发(35):使用Express Blend绘图 转:http://blog.csdn.net/tcjiaan/article/details/7493010...
查看>>
Windows Phone开发(33):路径之其它Geometry 转:http://blog.csdn.net/tcjiaan/article/details/7483835...
查看>>
Android入门(9)AudioRecord和AudioTrack类的使用【转】http://blog.sina.com.cn/s/blog_6309e1ed0100j1rw.html...
查看>>
mybatis整合Spring编码
查看>>
第七章 路由 68 路由-前端路由和后端路由的概念
查看>>
dpkg包管理
查看>>
前端JS利用canvas的drawImage()对图片进行压缩
查看>>
一键切换皮肤的解决思想及iframe嵌套时寻找下级iframe的方法
查看>>
van-dialog 组件调用 报错
查看>>
VC++中的__super::
查看>>
DS1-14
查看>>
c# Mongodb两个字段不相等 MongoDB原生查询
查看>>
排序算法-冒泡排序
查看>>
finally 的作用是什么?
查看>>
嵌入式Linux的调试技术
查看>>
CSS3
查看>>
用友U9 基础使用文件所在目录
查看>>
iOS CALayer 学习(1)
查看>>