1.岛屿的最大面积
class Solution { public: int maxAreaOfIsland(vector<vector<int>>& grid) { if(grid.size()==0)return 0; int n=grid.size(); int m=grid[0].size(); int max=0; vector<vector<bool>>visited(n,vector<bool>(m,false)); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(grid[i][j]==1&&visited[i][j]==false){ int tmp=cal_area(grid,i,j,n,m,visited); max=tmp>max?tmp:max; } } } return max; } int cal_area(vector<vector<int>>& grid,int i,int j,int rows,int cols,vector<vector<bool>>&visited){ if(i>=0&&i<rows&&j>=0&&j<cols&&grid[i][j]==1&&visited[i][j]==false){ visited[i][j]=true; return 1+cal_area(grid,i+1,j,rows,cols,visited)+cal_area(grid,i-1,j,rows,cols,visited)+cal_area(grid,i,j-1,rows,cols,visited) +cal_area(grid,i,j+1,rows,cols,visited); } else{ return 0; } } };
2.岛屿的个数
class Solution { public: int numIslands(vector<vector<char>>& grid) { if (grid.empty() || grid[0].empty()) return 0; int n=grid.size(); int m=grid[0].size(); vector<vector<bool>>visited(n,vector<bool>(m,false)); int res=0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == '1' && !visited[i][j]) { help(grid,i,j,n,m,visited); ++res; } } } return res; } void help(vector<vector<char> > &grid, int x, int y, int n,int m,vector<vector<bool>>&visited) { if (x >= 0 && x < n&& y >= 0 && y < m && grid[x][y] == '1' && visited[x][y] == false){ visited[x][y] = true; help(grid, x - 1, y, n, m, visited); help(grid, x + 1, y, n, m, visited); help(grid, x, y - 1, n, m, visited); help(grid, x, y + 1, n, m, visited); } } };