文章目录
- 一、题目
- 二、题解
一、题目
You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
Return the size of the largest island in grid after applying this operation.
An island is a 4-directionally connected group of 1s.
Example 1:
Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:
Input: grid = [[1,1],[1,0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:
Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can’t change any 0 to 1, only one island with area = 4.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 500
grid[i][j] is either 0 or 1.
二、题解
class Solution {
public:int count = 0;int dirs[4][2] = {1,0,0,1,-1,0,0,-1};void dfs(vector<vector<int>>& grid,int x,int y,int mark){grid[x][y] = mark;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){dfs(grid,nextX,nextY,mark);count++;}}}int largestIsland(vector<vector<int>>& grid) {int m = grid.size(),n = grid[0].size();unordered_map<int,int> map;int mark = 2;bool allLand = true;for(int i = 0;i < m;i++){for(int j = 0;j < n;j++){count = 1;if(grid[i][j] == 0) allLand = false;if(grid[i][j] == 1){dfs(grid,i,j,mark);map[mark] = count;mark++;}}}if(allLand) return m * n;int res = 0;unordered_set<int> visitedGrid;//遍历所有值为0的节点for(int i = 0;i < m;i++){for(int j = 0;j < n;j++){int sum = 1;visitedGrid.clear();if(grid[i][j] == 0){for(int index = 0;index < 4;index++){int nextX = i + dirs[index][0];int nextY = j + dirs[index][1];if(nextX < 0 || nextX >= grid.size() || nextY < 0 || nextY >= grid[0].size()) continue;if (visitedGrid.count(grid[nextX][nextY])) continue;sum += map[grid[nextX][nextY]];visitedGrid.insert(grid[nextX][nextY]);}}res = max(res,sum);}}return res;}
};