695. Max Area of Island
/*
* @lc app=leetcode id=695 lang=cpp
*
* [695] Max Area of Island
*
* https://leetcode.com/problems/max-area-of-island/description/
*
* algorithms
* Medium (72.62%)
* Likes: 10244
* Dislikes: 212
* Total Accepted: 1M
* Total Submissions: 1.4M
* Testcase Example: '[[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]]'
*
* 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.
*
*
*/
// @lc code=start
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid)
{
int maxArea = 0;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
maxArea = max(maxArea, dfs(grid, i, j));
}
}
return maxArea;
}
int dfs(vector<vector<int>>& grid, int i, int j)
{
if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size() || grid[i][j] == 0)
{
return 0;
}
int area = 1;
grid[i][j] = 0;
vector<vector<int>> directions = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
for (const auto& dir : directions)
{
area += dfs(grid, i + dir[0], j + dir[1]);
}
return area;
}
};
// @lc code=end
- T:
- S:
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid)
{
int maxArea = 0;
vector<vector<int>> directions = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
if (grid[i][j] == 0) continue;
int area = 1;
queue<vector<int>> q;
q.push({i, j});
grid[i][j] = 0;
while (!q.empty())
{
auto node = q.front(); q.pop();
for (const auto& dir : directions)
{
int new_i = node[0] + dir[0];
int new_j = node[1] + dir[1];
if (new_i < 0 || new_j < 0 || new_i >= grid.size() || new_j >= grid[0].size() || grid[new_i][new_j] == 0)
continue;
grid[new_i][new_j] = 0;
area++;
q.push({new_i, new_j});
}
}
maxArea = max(maxArea, area);
}
}
return maxArea;
}
};
- T:
- S: