DFS、BFS的定义及C语言算法实现请参照
连通图遍历策略之深度优先搜索(C语言)
连通图遍历策略之广度优先搜索(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.LinkedList;
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;}
}
下面是一个全排列的简单题目,也用到了dfs,属于偏简单的一道题目,用来给后面的题目做铺垫
问题描述:假设有编号为1、2、3的三张卡片和编号1、2、3的三个盒子,现需将这三张扑克牌分别放到三个盒子里面,并且每个盒子只能放一张扑克牌,请问一共有几种不同的方法?
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;}}