leetcode 695. Max Area of Island 深度优先遍历DFS
来源:互联网 发布:2017音乐软件市场份额 编辑:程序博客网 时间:2024/05/17 16:55
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.
本题题意很简单,就是计算面积最大的岛,直接深度优先遍历DFS即可,
代码如下:
#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>#include <regex>using namespace std;class Solution{public: int res = 0; int maxAreaOfIsland(vector<vector<int>>& grid) { int row = grid.size(), col = grid[0].size(); vector<vector<bool>> visit(row, vector<bool>(col, false)); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (grid[i][j] == 1) { int cur = 0; dfs(grid, visit, i, j, cur); } } } return res; } void dfs(vector<vector<int>>& a, vector<vector<bool>>& visit, int x, int y, int& cur) { int row = a.size(), col = a[0].size(); if (x < 0 || x >= row || y < 0 || y >= col || a[x][y] == 0 || visit[x][y] == true) return; else { visit[x][y] = true; cur+=1; res = max(res, cur); vector<vector<int>> dirs{ { 0,-1 },{ -1,0 },{ 0,1 },{ 1,0 } }; for (auto dir : dirs) dfs(a, visit, x + dir[0], y + dir[1], cur); } }};
- leetcode 695. Max Area of Island 深度优先遍历DFS
- leetcode 695. Max Area of Island岛的最大面积(深度优先搜索)
- DFS: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: Max Area of Island
- Max Area of Island(leetcode)
- leetCode-Max Area of Island
- leetcode 695. Max Area of Island——第一次成功的dfs
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- maven scope含义的说明
- [Leetcode] 554. Brick Wall 解题报告
- C++程序发开特点
- 通过opengl来实现yuv的显示
- shell脚本密码输入
- leetcode 695. Max Area of Island 深度优先遍历DFS
- Comparable与Comparator的具体应用场景
- RMI简单示例
- 【LDA】LDA主题模型
- 发布uap项目
- 3年工作经验的程序员应该具备的技能
- leetcode 696. Count Binary Substrings
- JPA一对多关系
- 分布式一致性系统的动态替换实现机制