CF1034D Intervals of Intervals
阿新 • • 發佈:2021-07-13
https://leetcode-cn.com/problems/max-area-of-island/
695. 島嶼的最大面積
給定一個包含了一些0
和1
的非空二維陣列grid
。
一個島嶼是由一些相鄰的1
(代表土地) 構成的組合,這裡的「相鄰」要求兩個1
必須在水平或者豎直方向上相鄰。你可以假設grid
的四個邊緣都被0
(代表水)包圍著。
找到給定的二維陣列中最大的島嶼面積。(如果沒有島嶼,則返回面積為0
。)
示例 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]]
對於上面這個給定矩陣應返回6
。注意答案不應該是11
,因為島嶼只能包含水平或垂直的四個方向的1
。
示例 2:
[[0,0,0,0,0,0,0,0]]
對於上面這個給定的矩陣, 返回0
。
注意:給定的矩陣grid
的長度和寬度都不超過 50。
DFS + 剪枝
class Solution { public: int move_[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; bool map_[55][55]; int dfs(int x, int y, int spuare, int row, int col, vector<vector<int>>& grid){ for(int i = 0; i<4; i++){ int x_ = x+move_[i][0]; int y_ = y+move_[i][1]; if(x_>=0 && y_>=0 && y_<col && x_<row && !map_[x_][y_] && grid[x_][y_]){ map_[x_][y_] = 1; spuare= max(spuare, dfs(x_, y_, spuare+1, row, col, grid)); } } return spuare; } int maxAreaOfIsland(vector<vector<int>>& grid) { int rows = grid.size(); int cols = grid[0].size(); int ans = 0; for(int i = 0; i<rows; i++){ for(int j = 0; j<cols; j++){ if(!map_[i][j] && grid[i][j]){ map_[i][j] = 1; ans = max(ans, dfs(i, j, 1, rows, cols, grid)); } } } return ans; } };