// 处理四个边界
for(int i = 0;i < m;i++){
// 左
if(grid[i][0] == 1) dfs(grid, i, 0, m, n);
// 右
if(grid[i][n - 1] == 1) dfs(grid, i, n - 1, m, n);
}
for(int i = 0;i < n;i++){
// 上
if(grid[0][i] == 1) dfs(grid, 0, i, m, n);
//下
if(grid[m - 1][i] == 1) dfs(grid, m - 1, i, m, n);
}
public void dfs(int[][] grid, int i, int j, int m, int n){
if(i >=m || i < 0 || j >= n || j < 0 || grid[i][j] == 0){
return;
}
grid[i][j] = 0;
count++;
dfs(grid, i + 1, j, m, n);
dfs(grid, i - 1, j, m, n);
dfs(grid, i, j + 1, m, n);
dfs(grid, i, j - 1, m, n);
}
整体代码如下:
public class NumEnclaves {
int count = 0;
/**
* 解决思路和Solve一样,都是从四个边开始出发,将与边界相连的1都置为0,之后,再重新计算1的数量即可
* @param grid
* @return
*/
public int numEnclavesWithDfs(int[][] grid) {
int m = grid.length, n = grid[0].length;
for(int i = 0;i < m;i++){
if(grid[i][0] == 1) dfs(grid, i, 0, m, n);
if(grid[i][n - 1] == 1) dfs(grid, i, n - 1, m, n);
}
for(int i = 0;i < n;i++){
if(grid[0][i] == 1) dfs(grid, 0, i, m, n);
if(grid[m - 1][i] == 1) dfs(grid, m - 1, i, m, n);
}
count = 0;
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
if(grid[i][j] == 1){
dfs(grid, i, j, m, n);
}
}
}
return count;
}
public void dfs(int[][] grid, int i, int j, int m, int n){
if(i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) return;
grid[i][j] = 0;
count++;
dfs(grid, i, j + 1, m, n);
dfs(grid, i, j - 1, m, n);
dfs(grid, i - 1, j, m, n);
dfs(grid, i + 1, j, m, n);
}
}
public class NumEnclaves {
boolean[][] visited;
int count = 0;
public int numEnclaves(int[][] grid) {
int m = grid.length, n = grid[0].length;
visited = new boolean[m][n];
for(int i = 0;i < m;i++){
if(grid[i][0] == 1) dfsWithVisited(grid, i, 0, m, n);
if(grid[i][n - 1] == 1) dfsWithVisited(grid, i, n - 1, m, n);
}
for(int i = 0;i < n;i++){
if(grid[0][i] == 1) dfsWithVisited(grid, 0, i, m, n);
if(grid[m - 1][i] == 1) dfsWithVisited(grid, m - 1, i, m, n);
}
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
if(grid[i][j] == 1 && !visited[i][j]){
count++;
}
}
}
return count;
}
public void dfsWithVisited(int[][] grid, int i, int j, int m, int n){
if(i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) return;
grid[i][j] = 0;
visited[i][j] = true;
dfsWithVisited(grid, i, j + 1, m, n);
dfsWithVisited(grid, i, j - 1, m, n);
dfsWithVisited(grid, i - 1, j, m, n);
dfsWithVisited(grid, i + 1, j, m, n);
}
}