给你一个大小为 m x n
的二进制矩阵 grid
。
岛屿 是由一些相邻的 1
(代表土地) 构成的组合,这里的「相邻」要求两个 1
必须在 水平或者竖直的四个方向上 相邻。你可以假设 grid
的四个边缘都被 0
(代表水)包围着。
岛屿的面积是岛上值为 1
的单元格的数目。
计算并返回 grid
中最大的岛屿面积。如果没有岛屿,则返回面积为 0
。
示例 1:
输入: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]] 输出:6 解释:答案不应该是 11 ,因为岛屿只能包含水平或垂直这四个方向上的 1 。
示例 2:
输入:grid = [[0,0,0,0,0,0,0,0]] 输出:0
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
为 0
或 1
1 class Solution { 2 public: 3 static constexpr int g_direciton[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; // 上、左、下、右四个方向 4 void bfs(vector<vector<int>> &graph, int x, int y, vector<vector<bool>> &visited, int &cnt) { 5 int row = graph.size(); 6 int col = graph[0].size(); 7 queue<std::pair<int, int>> q; // 存储坐标位置 8 q.push(make_pair(x, y)); 9 visited[x][y] = true; 10 cnt = 1; 11 while (!q.empty()) { 12 int size = q.size(); 13 for (int i = 0; i < size; i++) { 14 std::pair<int, int> position = q.front(); 15 q.pop(); 16 // 向四个方向遍历,坐标有效、值为1(陆地)且未被访问过的坐标入队 17 for (int j = 0; j < 4; j++) { 18 int xNext = position.first + g_direciton[j][0]; 19 int yNext = position.second + g_direciton[j][1]; 20 if (((xNext >=0 && xNext < row) && (yNext >=0 && yNext < col)) && 21 graph[xNext][yNext] == 1 && !visited[xNext][yNext]) { 22 q.push(make_pair(xNext, yNext)); 23 visited[xNext][yNext] = true; 24 cnt++; 25 } 26 } 27 } 28 } 29 } 30 int maxAreaOfIsland(vector<vector<int>>& grid) { 31 if (grid.size() == 0 || grid[0].size() == 0) { 32 return 0; 33 } 34 int row = grid.size(); 35 int col = grid[0].size(); 36 vector<vector<bool>> visited(row, vector<bool>(col, false)); 37 int maxNum = 0; 38 for (int i = 0; i < row; i++) { 39 for (int j = 0; j < col; j++) { 40 // 非陆地则跳过 41 if (grid[i][j] == 0) { 42 continue; 43 } 44 // 访问过则跳过 45 if (visited[i][j]) { 46 continue; 47 } 48 int cnt = 0; 49 bfs(grid, i, j, visited, cnt); 50 maxNum = max(maxNum, cnt); 51 } 52 } 53 return maxNum; 54 } 55 };