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
| class Solution { public: vector<vector<bool>> visted; int ROWCNT; int CLOWNCNT; int tempSize; void dfs(int x, int y, vector<vector<int>>& grid) { visted[x][y] = true; pair<int, int> neigbors[4]{ pair<int, int>(x, y + 1), pair<int, int>(x + 1, y), pair<int, int>(x, y - 1), pair<int, int>(x - 1, y)}; for (pair<int, int> neigbor : neigbors) { if (neigbor.first >= ROWCNT || neigbor.second >= CLOWNCNT || neigbor.first < 0 || neigbor.second < 0) continue; if (grid[neigbor.first][neigbor.second] != 1) continue; if (visted[neigbor.first][neigbor.second]) continue; dfs(neigbor.first, neigbor.second,grid); visted[x][y] = true; tempSize+=1; } }
int maxAreaOfIsland(vector<vector<int>>& grid) { ROWCNT = grid.size(); CLOWNCNT = grid[0].size(); visted = vector<vector<bool>>(ROWCNT, vector<bool>(CLOWNCNT, false)); int maxSize = 0; for (int i = 0; i < ROWCNT; i++) { for (int j = 0; j < CLOWNCNT; j++) { if (grid[i][j] == 1 && !visted[i][j]) { tempSize = 1; dfs(i, j, grid); maxSize = std::max(tempSize,maxSize); } } } return maxSize; } };
|