# 搜素算法（基础）--DFS/BFS算法（JAVA）

DFS、BFS的定义及C语言算法实现请参照

Input:
5 5
1 2
1 3
1 5
2 4
3 5
Output:
1 2 4 3 5

DFS

import java.util.Scanner;

public class DFS {
static int[][] e = new int[100][100];
static int[] book = new int[100];
static int n, m;
static int sum = 0;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
n = input.nextInt();
m = input.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (i == j) {
e[i][j] = 0;
} else {
e[i][j] = 99999999;
}
}
}
for (int i = 1; i <= m; i++) {
int a = input.nextInt();
int b = input.nextInt();
e[a][b] = 1;
e[b][a] = 1;
}
book[1] = 1;
dfs(1);
}
public static void dfs(int cur) {
System.out.print(cur + " ");
sum++;
if (sum == n) {
return;
}
for (int i = 1; i <= n; i++) {
if (e[cur][i] == 1 && book[i] == 0) {
book[i] = 1;
dfs(i);
}
}
return;
}
}


BFS


import java.util.Queue;
import java.util.Scanner;

public class BFS {
static int[][] e = new int[100][100];
static int[] book = new int[100];
static int n, m;
static Queue<Integer> queue = new LinkedList<>();
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int a, b;
n = input.nextInt();
m = input.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i == j) {
e[i][j] = 0;
} else {
e[i][j] = 99999999;
}
}
}
for (int i = 1; i <= m; i++) {
a = input.nextInt();
b = input.nextInt();
e[a][b] = 1;
e[b][a] = 1;
}
queue.offer(1);
book[1] = 1;
bfs();

}
public static void bfs() {
while (!queue.isEmpty()) {
int cur = queue.peek();
for (int i = 1; i <= n; i++) {
if (e[cur][i] == 1 && book[i] == 0) {
book[i] = 1;
queue.offer(i);
}
}
System.out.print(queue.remove() + " ");
}
return;
}
}


Output：
123 132 213 231 312 321

import java.util.Scanner;
/**
* DFS算法基本模型：
* void dfs(int step) {
*     判断边界
*     尝试每一种可能 for {
*         继续下一步def(step + 1)
*     }
*     返回
* }
* */

public class DFS {
static int n;
static int[] book = new int[10];
static int[] a = new  int[10];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
n = input.nextInt();
dfs(1);
}

public static void dfs(int step) {
if (step == n + 1) {
/**
* 打印，并返回
* */
for (int i = 1; i <= n; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
return;
}
for (int i = 0; i < n; i++) {
/**
* 标记数组book，用来检测盒子中是否已经放入
* */
if (book[i] == 0) {
/**
* 将i号扑克牌放入到第step个盒子中
* */
a[step] = i;
book[i] = 1;
/**
* 处理step+1个小盒子，注意要记得将刚才尝试的扑克牌收回
* */
dfs(step + 1);
book[i] = 0;
}
}
return;
}

}


©️2019 CSDN 皮肤主题: 点我我会动 设计师: 上身试试