一、DFS
1.排列数字
#include<bits/stdc++.h>
using namespace std;
const int N=10;
int path[N];
bool st[N];
int n;
int main(){
void dfs(int x);
cin >> n;
dfs(1);
return 0;
}
void dfs(int x){
if(x > n){
for(int i=1; i<=n;i++)
cout << path[i] << " ";
cout<<endl;
}
for(int i=1;i<=n;i++){ //空位可以选择的数据为1-n;
if(!st[i]){
path[x]=i;//把i存入路径中;
st[i]=true;
dfs(x+1);
st[i]=false;
}
}
}
用字典序输出,需要用到DFS。由布尔变量st判断是否遍历,将每一位未遍历的数存入path之中.
2.n皇后问题
#include<bits/stdc++.h>
using namespace std;
const int N=10;
char path[N][N];
int n;
bool col[N],udg[N*N],dg[N*N];
void dfs(int x){
if(x==n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<path[i][j];
}
// puts(path[i]);
cout<<endl;
// puts("");
}
cout<<endl;
return ;
}
for(int i=0;i<n;i++){
if(!col[i]&&!udg[x+i]&&!dg[n-x+i]){
path[x][i]='Q';
col[i]=udg[x+i]=dg[n-x+i]=1;
dfs(x+1);
col[i]=udg[x+i]=dg[n-x+i]=0;
path[x][i]='.';
}
}
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
path[i][j]='.';
}
}
dfs(0);
return 0;
}
这题中,如果使用puts函数,则不用加多余的cout<<endl;puts()会自动在输出结束后加一个换行;
1. puts()函数包含在头文件<stdio.h>中
2. 可以将字符串直接写入puts()。如:puts("hello world");因为字符串常量的话,本身也代表一个地址,其代表这个字符串第一个字符的地址。
3. puts()只能输出字符串,不能输出数值或者进行格式转换,即不能要求输出格式增加空格、换行(指的是输出内容的中间进行换行)等要求。
4. puts在输出字符串后会自动输出(追加)一个回车符。
5. 你会发现,puts()函数的返回值是0.
原文链接:https://blog.csdn.net/Elon_520/article/details/128510349