99.岛屿数量 深搜
注意深搜的两种写法,熟练掌握这两种写法 以及 知道区别在哪里,才算掌握的深搜。
方法1:加终止条件
import java.util.Scanner;
public class Main{
public static int[][] dirc = new int[][]{
{0,1} ,{1,0},{-1,0},{0,-1}};
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] graph = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
graph[i][j] = scanner.nextInt();
}
}
boolean[][] visited = new boolean[n][m];
int res = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(visited[i][j] == false && graph[i][j] == 1){
res++;
dfs(visited, graph, i , j);
}
}
}
System.out.println(res);
}
public static void dfs(boolean[][] visited, int[][] graph, int x, int y){
if(!(x >= 0 && x < graph.length && y >= 0 && y < graph[0].length)){
return;
}
if(!(visited[x][y] == false && graph[x][y] == 1)){
return;
}
visited[x][y] = true;
for(int i = 0; i < dirc.length; i++){
int nextx = x + dirc[i][0];
int nexty = y + dirc[i][1];
dfs(visited, graph, nextx, nexty);
}
}
}
方法2:不加终止条件
import java.util.Scanner;
public class Main{
public static int[][] dirc = new int[][]{
{0,1} ,{1,0},{-1,0},{0,-1}};
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] graph = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
graph[i][j] = scanner.nextInt();
}
}
boolean[][] visited = new boolean[n][m];
int res = 0;
for(int i = 0; i < n; i++){