Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.
Solutions
DFS
classSolution {public:intmaxAreaOfIsland(vector<vector<int>>& grid) {int m =grid.size();int n =grid[0].size(); vector<vector<int>>visited(m,vector<int>(n));int area =0;for(int i =0; i < m; ++i){for(int j =0; j < n; ++j){ area =max(area,dfs(grid, visited, i, j)); } }return area; }intdfs(vector<vector<int>> &grid,vector<vector<int>> &visited,int i,int j){ // if this is not an island or the island has been explored.if(grid[i][j] ==0||visited[i][j] ==1) return0;int area =1;visited[i][j] =1;if(i >0) area +=dfs(grid, visited, i -1, j);if(i +1<grid.size()) area +=dfs(grid, visited, i +1, j);if(j >0) area +=dfs(grid, visited, i, j -1);if(j +1<grid[0].size()) area +=dfs(grid, visited, i, j +1);return area; }};
BFS
classSolution {public:intmaxAreaOfIsland(vector<vector<int>>& grid) {int m =grid.size();int n =grid[0].size(); vector<vector<int>>visited(m,vector<int>(n));int area =0;for(int i =0; i < m; ++i){for(int j =0; j < n; ++j){ area =max(area,bfs(grid, visited, i, j)); } }return area; }intbfs(vector<vector<int>> &grid,vector<vector<int>> &visited,int i,int j){ // if this is not an island or the island has been explored.if(grid[i][j] ==0||visited[i][j] ==1) return0; queue<pair<int,int>> q;int area =0;visited[i][j] =1; // q: the frontier of the explored region of the current island.q.emplace(i, j);while(!q.empty()){++area;auto p =q.front();q.pop();int x =p.first, y =p.second;if(x >0&&grid[x -1][y] ==1&&visited[x -1][y] ==0){visited[x -1][y] =1;q.emplace(x -1, y); }if(x +1<grid.size() &&grid[x +1][y] ==1&&visited[x +1][y] ==0){visited[x +1][y] =1;q.emplace(x +1, y); }if(y >0&&grid[x][y -1] ==1&&visited[x][y -1] ==0){visited[x][y -1] =1;q.emplace(x, y -1); }if(y +1<grid[0].size() &&grid[x][y +1] ==1&&visited[x][y +1] ==0){visited[x][y +1] =1;q.emplace(x, y +1); } }return area; }};