Depth-first search, also known as dfs, is a search algorithm. The best practice for this kind of algorithm is topic practice. Here are a few examples to explain dfs
Example 1: Enter n, please output the full arrangement of 1-n
深度优先搜索的思路如下
public static void dfs(int step){
判断边界,递归的出口
for(尝试每一种可能){
继续下一步dfs(step+1)
}
}
Here suppose n = 3, then it is to solve the whole arrangement of 1-3, because the simple can easily get the answer
123,132,213,231,312,321
Then the idea of using dfs is that the specific code is as follows
public static void dfs(int step){
if(step == 4){
打印前三步排好的数字
}
从1-3开始看看能不能排
dfs(step+1)
}
package com.note;
import java.util.Scanner;
/**
* 输入n
* 输出1-n的全排列
*/
public class dfs数的全排列 {
private static int n;
private static int[] arr;
private static int[] book;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
arr = new int[n+1];
book = new int[n+1];
dfs(1);
}
private static void dfs(int step) {
if (step == n+1){
for (int i=1;i<=n;i++)
System.out.print(arr[i]);
System.out.println();
return;
}
for (int i=1;i<=n;i++){
if (book[i] == 0){
book[i] = 1;
arr[step] =i;
dfs(step+1);
book[i] = 0;
}
}
}
}