classSolution { public: intnumIslands(vector<vector<char>>& grid){ int m = grid.size(), n = grid[0].size(); int res = 0; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(grid[i][j] == '1'){ res++; dfs(grid, i, j); } } } return res; } int dx[4] = {0,0,1,-1}; int dy[4] = {1,-1,0,0}; voiddfs(vector<vector<char> >& grid, int x, int y){ //base case int m = grid.size(), n = grid[0].size(); if(x < 0 || y < 0 || x >= m || y < 0 || y >= n) return; //已经是水了 if(grid[x][y] == '0') return; //淹没 grid[x][y] = '0'; for(int i = 0; i < 4; i++){ int nx = x + dx[i]; int ny = y + dy[i]; dfs(grid, nx, ny); } } };
classSolution { public: int m, n; intclosedIsland(vector<vector<int>>& grid){ m = grid.size(), n = grid[0].size(); for(int i = 0; i < n; i++){ //处理上边界 dfs(grid, 0, i); //处理下边界 dfs(grid, m - 1, i); } for(int i = 0; i < m; i++){ //处理左边界 dfs(grid, i, 0); //处理右边界 dfs(grid, i, n - 1); } //遍历grid,剩下的岛屿就是封闭岛屿 int res = 0; for(int i = 1; i < m - 1; i++){ for(int j = 1; j < n - 1; j++){ if(grid[i][j] == 0){ res++; dfs(grid, i, j); } } } return res; } int dx[4] = {0,0,1,-1}; int dy[4] = {1,-1,0,0}; voiddfs(vector<vector<int> >& grid, int x, int y){ //base case if(x < 0 || y < 0 || x >= m || y >= n) return; if(grid[x][y] == 1) return; //淹没 grid[x][y] = 1; for(int i = 0; i < 4; i++){ int nx = x + dx[i]; int ny = y + dy[i]; dfs(grid, nx, ny); } } };
classSolution { public: int dx[4] = {0,0,1,-1}; int dy[4] = {-1,1,0,0}; intnumEnclaves(vector<vector<int>>& grid){ //从边界开始dfs,然后把能去到的岛屿淹没,最后遍历剩余的1的个数即为答案 int m = grid.size(), n = grid[0].size(); for(int i = 0; i < n; i++){ //从上面开始淹没 dfs(grid, 0, i); //从下面开始淹没 dfs(grid, m - 1, i); } for(int j = 0; j < m; j++){ //从左边开始淹没 dfs(grid, j, 0); //从右边开始淹没 dfs(grid, j, n - 1); } int res = 0; //遍历输出 1 的个数 for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(grid[i][j] == 1){ res++; } } } return res; } voiddfs(vector<vector<int> >& grid, int x, int y){ int m = grid.size(), n = grid[0].size(); //base case if(x < 0 || y < 0 || x >= m || y >= n) return; if(grid[x][y] == 0) return; //把岛屿淹没 grid[x][y] = 0; for(int i = 0; i < 4; i++){ int nx = x + dx[i]; int ny = y + dy[i]; dfs(grid, nx, ny); } } };
classSolution { public: intmaxAreaOfIsland(vector<vector<int> >& grid){ int m = grid.size(), n = grid[0].size(); int res = 0; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(grid[i][j] == 1){ int ans = dfs(grid, i, j); res = max(res, ans); } } } return res; } intdfs(vector<vector<int> >& grid, int x, int y){ int m = grid.size(), n = grid[0].size(); //base case if(x < 0 || y < 0 || x >= m || y >= n) return0; if(grid[x][y] == 0) return0; //淹没成水 grid[x][y] = 0; returndfs(grid, x + 1, y) + dfs(grid, x, y + 1) + dfs(grid, x - 1, y) + dfs(grid, x, y - 1) + 1; } };