Max Area of Island(leetcode)
来源:互联网 发布:淘宝拍照用什么手机 编辑:程序博客网 时间:2024/06/05 21:09
Max Area of Island
- 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 {public: int maxAreaOfIsland(vector<vector<int>>& grid) { int result = 0; int row = grid.size(); if (row == 0) return result; int col = grid[0].size(); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (grid[i][j] == 1) { // 判断grid[i][j]附近是否存在着相邻的 土地 int temp = searchArea(grid, i, j); result = (result < temp) ? temp : result; } } } return result; } int searchArea(vector<vector<int>>& grid, int i, int j) { int result = 0; int row = grid.size(); if (row == 0) return result; int col = grid[0].size(); if (i >= 0 && i < row && j >= 0 && j < col && grid[i][j] == 1) { grid[i][j] = -1; // 将数过的土地作标志,避免重复数数 // 计算附近相邻土地数量 result = searchArea(grid, i + 1, j) + searchArea(grid, i - 1, j) + searchArea(grid, i, j + 1) + searchArea(grid, i, j - 1); return result + 1; } return result; }};
阅读全文
0 0
- LeetCode: Max Area of Island
- Max Area of Island(leetcode)
- leetCode-Max Area of Island
- leetcode 695. Max Area of Island 解法
- leetcode 695(Max Area of Island)
- [LeetCode] Algorithms-695. Max Area of Island
- leetcode 695 Max Area of Island
- Leetcode 695. Max Area of Island
- LeetCode-695. Max Area of Island
- LeetCode 695. Max Area of Island
- LeetCode-695. Max Area of Island
- [LeetCode] 695. Max Area of Island
- 【LeetCode】695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- Dilated Residual Networks
- Go游戏服务器开发的一些思考(二十六):Go Redis ORM库
- Java修饰符指代的访问权限
- java 自我知识总结 (十九)lamdba表达式和内部类
- Spring+SpringMVC+Mybatis
- Max Area of Island(leetcode)
- How can i use iptables on centos 7
- Spring
- 8086汇编学习
- GB18030编码
- yum安装的httpd配置多个虚拟主机、配置8080端口、访问phpMyAdmin
- CS231n(2):课程作业# 1简介
- scanner 中的next() 和nextline()区别
- 墨刀初试