全排序dfs
https://www.acwing.com/problem/content/844/
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
import java.util.*;
public class Main{
static int N = 10,n;
static int[] path = new int[N];
static boolean[] st = new boolean[N];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
dfs(0);
}
//回溯时循环没结束,进行循环,循环结束时,往上一层回溯
//for循环里面dfs调用结束之后,返回dfs这地方,继续执行dfs的下一条语句,
//再加上外面的for循环,要从1到3,完成回溯的
private static void dfs(int u){
if(u==n){
for(int i = 0; i < n; i++){
System.out.print(path[i] + " ");
}
System.out.println();
return;
}
for(int i = 1; i <= n; i++){
if(!st[i]){
path[u] = i;
st[i] = true;
dfs(u + 1);
st[i] = false;
}
}
}
}
关键点
for(int i=1;i<=n;i++) //未搜素完成则继续尝试 即一条走到底为止
{
if(!st[i])
{
st[i]=true; //标记当前步防止重复
path[u]=i; //保存当前路径
dfs(u+1); //进行下一步搜索
st[i]=false; //恢复现场 否则会影响下一条路的搜索
// path[u]=0;
}
}
递归时回溯回来的时候循环没有结束是进行循环也就说
1->dfs(1)->2->dfs(2)->3->dfs(3) 这个时候一条路径走完,循环遍历return就开始回溯。回溯回来是从dfs(u + 1);回来的这个时候恢复现场。
n皇后
https://www.acwing.com/problem/content/845/
import java.util.*;
public class Main{
static int n;
static int N = 20;
static char[][] num = new char[N][N];
static boolean[] col = new boolean[N], dg = new boolean[N], udg = new boolean[N];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
num[i][j] = '.';
}
}
dfs(0);
}
public static void dfs(int u ){
if (u == n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(num[i][j]);
}
System.out.println();
}
System.out.println();
return;
}
for (int i = 0; i < n; i++)
{
if (!col[i] && !dg[i - u + n] && !udg[i + u])
{
num[u][i] = 'Q';
col[i] = dg[i - u + n] = udg[i + u] = true;
dfs(u + 1);
col[i] = dg[i - u + n] = udg[i + u] = false;
num[u][i] = '.';
}
}
}
}
解析:
https://www.acwing.com/solution/content/2820/
for (int i = 0; i < n; i++)
{
if (!col[i] && !dg[i - u + n] && !udg[i + u])
{
num[u][i] = 'Q';
col[i] = dg[i - u + n] = udg[i + u] = true;
dfs(u + 1);
col[i] = dg[i - u + n] = udg[i + u] = false;
num[u][i] = '.';
}
}