1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| class Solution { public: int maxAreaOfIsland(vector<vector<int>>& grid) { int n = grid.size(); int m = grid[0].size();
if (n == 0) { return 0; }
vector<vector<bool>> vis; for (int i = 0; i < n; i++) { vector<bool> col; for (int j = 0; j < m; j++) { col.push_back(false); } vis.push_back(col); } int max = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!vis[i][j]) { int tmp = go(i, j, n, m, vis, grid); if (tmp > max) { max = tmp; } } } }
return max; }
int go(int i, int j, const int& n, const int& m, vector<vector<bool>>& vis, vector<vector<int>>& grid) {
vis[i][j] = true;
int area = 0;
if (grid[i][j]) { area = 1; if (i - 1 >= 0 && !vis[i-1][j]) { area += go(i-1, j, n, m, vis, grid); } if (i + 1 < n && !vis[i+1][j]) { area += go(i+1, j, n, m, vis, grid); } if (j - 1 >= 0 && !vis[i][j-1]) { area += go(i, j-1, n, m, vis, grid); } if (j + 1 < m && !vis[i][j+1]) { area += go(i, j+1, n, m, vis, grid); } }
return area; } };
|