本文主要是介绍LeetCode695. Max Area of Island,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 一、题目
- 二、题解
一、题目
You are given an m x n binary matrix grid. 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.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an island in grid. If there is no island, return 0.
Example 1:
Input: grid = [[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]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.
Example 2:
Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j] is either 0 or 1.
二、题解
class Solution {
public:int count = 1;int dirs[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};void dfs(vector<vector<int>>& grid,vector<vector<bool>>& visted,int x,int y){for(int i = 0;i < 4;i++){int nextX = x + dirs[i][0];int nextY = y + dirs[i][1];if(nextX < 0 || nextX >= grid.size() || nextY < 0 || nextY >= grid[0].size()) continue;if(grid[nextX][nextY] == 1 && visted[nextX][nextY] == false){count++;visted[nextX][nextY] = true;dfs(grid,visted,nextX,nextY);}}}int maxAreaOfIsland(vector<vector<int>>& grid) {int m = grid.size();int n = grid[0].size();int res = 0;vector<vector<bool>> visted(m,vector<bool>(n,false));for(int i = 0;i < m;i++){for(int j = 0;j < n;j++){if(grid[i][j] == 1 && visted[i][j] == false){count = 1;visted[i][j] = true;dfs(grid,visted,i,j);res = max(res,count);}}}return res;}
};
这篇关于LeetCode695. Max Area of Island的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!