深度优先搜索关键在于解决“当下该如何做”。至于“下一步如何做”则与当下该如何做“是一样的。
深度优先搜索模型:
void dfs(int step){
判断边界,一般在这里输出最终的结果
尝试每一种可能for(int i=1;i<=n;i++)
{
标记
继续下一步dfs(step+1);
收回标记
}
返回
}
通常,需要book数组标记哪些牌已经使用或者记录格子已经在路径中(就是被使用)等等。使用过后一定要将book[i]收回
if (book[i]==0) {//将book[i]设为0,表示i号扑克牌还在手上
//开始尝试使用扑克牌
a[step]=i; //将i号扑克牌放到第step个盒子中
book[i]=1; //将book[i]设为1,表示i号扑克牌已经不在手上
//第step个盒子已经放好扑克牌,接下来需要走到下一个盒子面前
dfs(step+1);//通过递归处理第step+1个盒子
book[i]=0; //非常重要,一定要将刚才尝试的扑克牌收回,才能进行下一次尝试
}
if (a[tx][ty]==0&&book[tx][ty]==0) {
book[tx][ty]=1; //标记这个点已经走过
dfs(tx, ty, step+1); //尝试下一个点
book[tx][ty]=0; //尝试结束,取消这个点的标记
}
4-1 代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
const int max=1000;
int a[10],book[10],n;//c语言全局变量在没有赋值以前默认为0
void dfs(int step){ //step表示站在第几个盒子面前
if(step==n+1){ //如果站在第n+1个盒子面前,则表示前n个盒子已经放好扑克牌
//输出一种排列
for(int i=1;i<=n;i++)
printf("%d",a[i]);
printf(" ");
return; //return返回之前的一步,最近一次调用dfs函数的地方
}
//此时站在第step个盒子面前,应该放哪张牌呢?按照1,2,3···n的顺序试一下
for (int i=1; i<=n; i++) {
//判断扑克牌i是否还在手上
if (book[i]==0) {//将book[i]设为0,表示i号扑克牌还在手上
//开始尝试使用扑克牌
a[step]=i; //将i号扑克牌放到第step个盒子中
book[i]=1; //将book[i]设为1,表示i号扑克牌已经不在手上
//第step个盒子已经放好扑克牌,接下来需要走到下一个盒子面前
dfs(step+1);//通过递归处理第step+1个盒子
book[i]=0; //一定要将刚才尝试的扑克牌收回,才能进行下一次尝试
}
}
}
int main() {
scanf("%d",&n);//输入n为1~9之间的整数
dfs(1);
printf("\n");
return 0;
}
运行结果:
4-2代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
const int max=1000;
int p,q,min=999999999,n,m;
int book[51][51],a[51][51];
void dfs(int x,int y,int step){
int next[4][2]={
{0,1}, //向右走
{1,0}, //向下走
{0,-1}, //向左走
{-1,0} //向山走
};
int tx,ty;
//判断是否到达小哈的位置
if (x==p&&y==q) {
//更新最小值
if(step<min)
min=step;
return;
}
//枚举4种走法
for (int k=0; k<=3; k++) {
//计算下一个点的坐标
tx=x+next[k][0];
ty=y+next[k][1];
//判断是否越界
if(tx<1||tx>n||ty<1||ty>m)
continue;
//判断该点是否为障碍物或者已经在路径中
if (a[tx][ty]==0&&book[tx][ty]==0) {
book[tx][ty]=1; //标记这个点已经走过
dfs(tx, ty, step+1); //尝试下一个点
book[tx][ty]=0; //尝试结束,取消这个点的标记
}
}
}
int main() {
int startx,starty;
scanf("%d %d",&n,&m); //n行m列
//读入迷宫
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
scanf("%d",&a[i][j]);
//读入起点坐标和终点坐标
scanf("%d %d %d %d",&startx,&starty,&p,&q);
//从起点开始搜索
book[startx][starty]=1; //标记起点已经在路径,防止后面重复走
dfs(startx, starty, 0);
printf("%d\n",min);
return 0;
}