基本模板
int check(参数)
{
if(条件)
return 1;
else
return 0;
}
void DFS(int step)
{
判断边界
{
相应操作
}
尝试每一种可能
{
满足check条件
标记
继续下一步DFS(step+1)
恢复初始状态(回溯的时候使用)
}
}
剪枝
DFS的时间复杂度较BFS而言比较大,因此剪枝很重要
可行性剪枝
如果当前条件不合法就不再继续搜索,直接return。这是非
常好理解的剪枝。
最优性剪枝
如果当前条件所创造出的答案必定比之前的答案大,那么剩
下的搜索就毫无必要,甚至可以剪掉。我们利用某个函数估
计出此时条件下答案的‘下界’,将它与已经推出的答案相
比,如果不比当前答案小,就可以剪掉。尤其是求解迷宫最
优解时。
重复性剪枝
对于某一些特定的搜索方式,一个方案会被搜索很多次,这
样是没有必要的。
奇偶性剪枝
数的奇偶性对答案产生影响
几道比较经典的DFS例题
Fox And Two Dots-dfs
Fox Ciel is playing a mobile puzzle game called “Two Dots”. The basic levels are played on a board of size n × m cells, like this:
Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.
The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, …, dk a cycle if and only if it meets the following condition:
These k dots are different: if i ≠ j then di is different from dj.
k is at least 4.
All dots belong to the same color.
For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge.
Determine if there exists a cycle on the field.
Input
The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board.
Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.
Output
Output “Yes” if there exists a cycle, and “No” otherwise.
Examples
input
3 4
AAAA
ABCA
AAAA
output
Yes
input
3 4
AAAA
ABCA
AADA
output
No
input
4 4
YYYR
BYBY
BBBY
BBBY
output
Yes
input
7 6
AAAAAB
ABBBAB
ABAAAB
ABABBB
ABAAAB
ABBBAB
AAAAAB
output
Yes
input
2 13
ABCDEFGHIJKLM
NOPQRSTUVWXYZ
output
No
Note
In first sample test all ‘A’ form a cycle.
In second sample there is no such cycle.
The third sample is displayed on the picture above (‘Y’ = Yellow, ‘B’ = Blue, ‘R’ = Red).
从前到最后进行一次bfs,在每一个点向四周搜索(但是不能走回头路),每搜到一个点就用vis标记一下。
如果搜到了vis标记过的点,而且和这个点是同一种颜色,那么说明肯定打环了,说明就成立。
转载自:https://blog.csdn.net/wyg1997/article/details/52208683
代码
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
char str[53][53];
int vis[53][53];
int d[4][2]={1,0,-1,0,0,1,0,-1};
int n,m,ans,dx,dy;
void DFS(int x,int y,int nx,int ny) //nx,ny记录的是上一次跑图时经过的点,用来与下一次跑图时点的位置比较,看是否下一次点的位置是否回到上次点的位置
{
if(vis[x][y])
{
ans=1;
return;
}
vis[x][y]=1;
for(int i=0;i<4;i++)
{
dx=x+d[i][0];
dy=y+d[i][1];
if(dx==nx&&dy==ny)
continue;
if(dx>=0&&dy>=0&&dx<n&&dy<m&&str[dx][dy]==str[x][y])
{
DFS(dx,dy,x,y);
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m)){
for(int i=0;i<n;i++){
scanf("%s",str[i]);
}
memset(vis,false,sizeof(vis));
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(!vis[i][j]){
DFS(i,j,0,0);
}
if(ans){
break;
}
}
if(ans)
break;
}
if(ans)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}
N皇后问题
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1
8
5
0
Sample Output
1
92
10
这道题要注意把从1到10的结果打表,输出从表中输出,不然会超时。
代码
#include <stdio.h>
#include <stdlib.h>
#include<algorithm>
int queen[11], sum=0;
int method[11]={0}; //将结果打表
int n;
int check(int m){
int i;
for(i = 0; i < m; i++){
if(queen[i] == queen[m] || abs(queen[i] - queen[m]) == (m - i)){
return 0;
}
}
return 1;
}
void put(int m){
int i;
for(i = 0; i < n; i++){
queen[m] = i;
if(check(m)){
if(n == m + 1){
sum++;
}
else{
put(m + 1);
}
}
}
}
int main(){
while(~scanf("%d",&n),n){
sum=0;
if(method[n]!=0)
printf("%d\n",method[n]);
else{
put(0);
method[n]=sum;
printf("%d\n", sum);
}
}
return 0;
}
放苹果
把M个同样的苹果放在N个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法?(用K表示)5,1,1和1,5,1 是同一种分法。
Input
第一行是测试数据的数目t(0 <= t <= 20)。以下每行均包含二个整数M和N,以空格分开。1<=M,N<=10。
Output
对输入的每组数据M和N,用一行输出相应的K。
Sample Input
1
7 3
Sample Output
8
搜索终止条件,苹果树为1,那只有一种了;盘子为1,那全放进去,也是一种;当苹果数为0,题目中说允许有盘子空着不放,那这也算一种= =[金馆长脸]。
然后考虑边界,当m比n小,那剩余的盘子相当于无效,就继续dfs(m, m);
当m大于等于n的时候,就是我们平常的放法。而我们平常放时就有放满和不满的情况,不满的就dfs(m, n-1)继续往下搜,满的就dfs(m-n, n)往下搜。
ps:搜索这种题。。必须找到边界条件才能做,边界条件就很难找啊,以前上学时候哪有题是这样的,哎得多练。这题就是赤裸裸考你找边界,很好一道题,锻炼了思维。
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 100010;
const int INF = 0x3f3f3f3f;
int dfs(int m, int n)
{
if(m == 1 || n == 1 || m == 0) return 1;
if(m < n)
return dfs(m, m);
else
return dfs(m, n-1)+dfs(m-n, n);
}
int main()
{
// freopen("in.txt", "r", stdin);
int t, m, n, ans;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &m, &n);
ans = dfs(m, n);
printf("%d\n", ans);
}
return 0;
}
作者:Flynn_curry
来源:CSDN
原文:https://blog.csdn.net/flynn_curry/article/details/51484276
Tempter of the Bone
小明做了一个很久很久的梦,醒来后他竟发现自己和朋友在一个摇摇欲坠的大棋盘上,他们必须得想尽一切办法逃离这里。
经过长时间的打探,小明发现,自己所在的棋盘格子上有个机关,上面写着“你只有一次机会,出发后t秒大门会为你敞开”,而他自己所在的棋盘是大小为 N*M 的长方形,他可以向上下左右四个方向移动(不可走有障碍点)。棋盘中有一扇门。根据机关的提示,小明顿时明白了,他和朋友必须在第 t 秒到门口。而这一切,没有回头路!因为一旦他移动了,他刚才所在的点就会消失,并且他不能在一个点上停留超过一秒,不然格子会爆炸。大逃亡开始了,请问小明和朋友能安全的逃出这奇怪的棋盘吗?
Input
输入多组测试数据。每个测试用例的第一行包含三个整数 N、M 和 T ( 1 < N , M < 7 ; 0 < T < 50 ),分别表示棋盘的大小和门打开的时间。接下来的N行给出棋盘布局,每一行包含M个字符。其中
“.”: 无障碍点
“X”: 障碍点
“S”: 起点
“D”: 门
输入以 3 个 0 结束。这个测试用例不需要处理。
输入数据中的空格有些问题,请不要使用getchar(),如果一定要用可以选择scanf("%s",) 自动忽略空格
Output
对于每组样例输出一行。
如果小明能够安全逃出,输出 “YES” ,否则输出 “NO”。
Sample Input
4 4 5
S.X.
…X.
…XD
…
3 4 5
S.X.
…X.
…D
0 0 0
Sample Output
NO
YES
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
char map[10][10];
int visit[10][10];
int n,m,t,ex,ey,flag;
void dfs(int sx,int sy,int step)
{
int i,dx,dy;
int next[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
if(flag)//很重要,可以减少步骤,也是如何使一旦找到需要的路线就可以连续return出
return;
if(sx==ex&&sy==ey&&step==t)
{
flag=1;
return;
}
int tem=t-step-abs(ex-sx)-abs(ey-sy);//剪枝的核心代码
if(tem<0||tem&1)//剪枝:如果剩余的步数已经不足以走到出口,且必须是偶数,偶数-偶数=偶数,奇数-奇数=偶数,
return;
for(i=0;i<4;i++)
{
dx=sx+next[i][0];
dy=sy+next[i][1];
if(dx<0||dy>=m||dy<0||dx>=n)
continue;
if(map[dx][dy]!='X'&&visit[dx][dy]==0)
{
visit[dx][dy]=1;//及时标记,先判断后标记,先确定能不能走 ,在考虑走完标记的问题
dfs(dx,dy,step+1);
if(flag)//若找到结果,及时return
return;
visit[dx][dy]=0;//注意返回标记 以便下次搜索
}
}
return ;
}
int main()
{
int i,j;
int sx,sy;
while(~scanf("%d %d %d",&n,&m,&t))
{
if(n==0&&m==0&&t==0)
break;
flag=0;
memset(visit,0,sizeof(visit));
for(i=0;i<n;i++)
scanf("%s",map[i]);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
{
if(map[i][j]=='S')
sx=i;sy=j;
if(map[i][j]=='D')
ex=i;ey=j;
}
visit[sx][sy]=1;//务必记得标记走过的路径
dfs(sx,sy,0);
if(flag==1)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}