《算法笔记》8.1小节——搜索专题->深度优先搜索(DFS)
5972 Problem A 【递归入门】全排列
#include
const int maxn = 10000;
int a[maxn];
bool flag[maxn] = { false };
void combine(int cnt,int n) {
if (cnt == n) {
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return;
}
for (int i = 0; i < n; i++) {
if (flag[i] == false) {
a[cnt] = i + 1;
flag[i] = true;
combine(cnt + 1,n);
flag[i] = false;
}
}
}
int main() {
int n;
while (scanf("%d", &n) != EOF) {
int cnt = 0;
combine(cnt, n);
}
return 0;
}
5973 Problem B 【递归入门】组合的输出
#include
const int maxn = 10000;
int a[maxn];
void DFS(int cnt,int index,int n,int r) {
if (cnt > r) {
for (int i = 1; i <= r; i++)
printf("%d ", a[i]);
printf("\n");
return;
}
if (index > n) return;
a[cnt] = index;
DFS(cnt+1, index + 1, n, r); //加入此节点
DFS(cnt, index + 1, n, r); //不加此节点
}
int main() {
int n,r;
while (scanf("%d %d", &n,&r) != EOF) {
int cnt = 0;
DFS(1, 1, n, r);
}
return 0;
}
5974 Problem C 【递归入门】组合+判断素数
#include
#include
using namespace std;
const int maxn = 10000;
int a[maxn];
int n, k,num;
bool isprime(int sum) {
if (sum <= 1) return false;
else{
for (int i = 2; i <= sqrt(sum); i++) {
if (sum%i == 0) return false;
}
}
return true;
}
void DFS(int cnt, int sum,int index) {
if (cnt == k) {
if (isprime(sum)) num++;
return;
}
if (index == n) return;
DFS(cnt+1, sum + a[index], index+1);
DFS(cnt, sum, index+1);
}
int main() {
while (scanf("%d %d", &n,&k) != EOF) {
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
int sum = 0,cnt = 0,index=0;
num = 0;
DFS(cnt, sum, index);
printf("%d\n", num);
}
return 0;
}
5976 Problem D 【递归入门】n皇后 问题(原始的8皇后问题)
n皇后问题代码1
n皇后问题代码2
5977 Problem E 【递归入门】出栈序列统计
#include
int n,cnt;
void isstack(int popnum, int pushnum) {
if (pushnum == n || popnum == n) {
cnt++;
return;
}
isstack(popnum, pushnum + 1);
if (pushnum > popnum)
isstack( popnum + 1, pushnum);
return;
}
int main() {
while (scanf("%d", &n)!=EOF) {
cnt = 0;
int popnum = 0, pushnum = 0;
isstack(popnum, pushnum);
printf("%d\n", cnt);
}
return 0;
}
5978 Problem F 【递归入门】走迷宫
不想写了,老是错,我累了
#include
#include
using namespace std;
int dx[4]={0,-1,0,1},dy[4]={-1,0,1,0},a[20][20],x1,x2,y1,y2,m,n;//开两个一维数组比开一个二维数组要简洁明了一些,不会使代码冗长
struct node
{
int x,y;
}b[4400];//要学会用结构体,这是一个好东西
bool flag=false;
void print(int t)
{
flag=true;
for(int i=1;i<=t-1;++i) printf("(%d,%d)->",b[i].x,b[i].y);
printf("(%d,%d)",b[t].x,b[t].y);
printf("\n");
}
void dfs(int x,int y,int k)
{
b[k].x=x;b[k].y=y;
if(x==x2&&y==y2) print(k);
else
{
for(int i=0;i<=3;++i)
if((a[x+dx[i]][y+dy[i]]==1)&&(1<=x+dx[i]<=m)&&(1<=y+dy[i]<=n))
{
a[x+dx[i]][y+dy[i]]=0;
dfs(x+dx[i],y+dy[i],k+1);//坑死我的地方,千万不要写成k++
a[x+dx[i]][y+dy[i]]=1;
}
}
}
int main()
{
scanf("%d%d",&m,&n);
memset(a,0,sizeof(a));
for(int i=1;i<=m;++i)
for(int j=1;j<=n;++j)
scanf("%d",&a[i][j]);
scanf("%d%d",&x1,&y1);
scanf("%d%d",&x2,&y2);
a[x1][y1]=0;//开头赋值为false,以免又搜回来
dfs(x1,y1,1);
if(flag==false) printf("-1");
}