# 思路分析

### 检查函数

``````    private int[][] g;//矩阵
private int n, m;//矩阵的高和长
private boolean[][] visited;//判断结点是否访问过
private int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
public void dfs(int i, int j){
visited[i][j] = true;
for(int k = 0; k < 4; k++){
int a = i + dx[k];
int b = j + dy[k];
if(a >= 0 && a < n && b >= 0 && b < m && !visited[a][b] && g[a][b] == 1)
dfs(a, b);
}
}

public boolean check(){
visited = new boolean[n][m];
int cnt = 0;//连通块的数量

for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(!visited[i][j] && g[i][j] == 1){
dfs(i, j);
cnt++;
}
}
}
return cnt >= 2;
}
``````

# 完整代码

``````class Solution {

private int[][] g;//矩阵
private int n, m;//矩阵的高和长
private boolean[][] visited;//判断结点是否访问过
private int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};

public void dfs(int i, int j){
visited[i][j] = true;
for(int k = 0; k < 4; k++){
int a = i + dx[k];
int b = j + dy[k];
if(a >= 0 && a < n && b >= 0 && b < m && !visited[a][b] && g[a][b] == 1)
dfs(a, b);
}
}

public boolean check(){
visited = new boolean[n][m];
int cnt = 0;//连通块的数量

for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(!visited[i][j] && g[i][j] == 1){
dfs(i, j);
cnt++;
}
}
}
return cnt >= 2;
}

public int minDays(int[][] grid) {
n = grid.length;
m = grid[0].length;
g = grid;

if(check()){
return 0;
}

for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(g[i][j] == 1){
g[i][j] = 0;
if(check()){
return 1;
}
g[i][j] = 1;
}
}
}
return 2;
}
}
``````