DFS: staek space: O(n) does not have the shortest
BFS: queue space: O(2^n) can find the shortest path
DFS examples and code templates
topic description
Given an integer n, arrange the numbers 1∼n in a row, and there will be many ways to arrange them.
Now, please output all the permutation methods in lexicographical order.
Input format
A total of one line, including an integer nOutput format
Output all permutation schemes in lexicographical order, each scheme occupying one line.Data range
1≤n≤7
input sample3
output sample
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
#include<iostream>
using namespace std;
const int N = 10;
int n;
int path[N];
bool st[N];
void dfs(int u){
if(u==n){
for(int i=0;i<n;i++)
printf("%d ",path[i]);
puts("");//输出换行
return;
}
for(int i=1;i<=n;i++){
if(!st[i]){
path[u]=i;
st[i]=true;//标记某个数字已经使用
dfs(u+1);
st[i]=false;//还原某个数字的标记
}
}
}
int main(){
cin>>n;
dfs(0);
return 0;
}