众所周知,搜索是一种万能 常用的算法,几乎所有问题都可以用搜索来求解。它的基本思想是:穷举所有情况,其具体流程是,先选择某一种可能情况进行探索,并在这种情况的基础上不断尝试新的情况,一旦发现原来的选择是错误的,就退回一步重新选择,继续向前探索,如此反复进行,直至得到解或证明无解。
搜索一般有两种方式,即深度优先搜索(DFS)和广度优先搜索(BFS)
深度优先搜索(DFS):
思想:一直往深处走,直到找到解或者走不下去为止
例如:走迷宫的时候,在起点处,我们先任意选一个前进方向,到达新的位置后再次选择新的方向进行尝试,如果碰到死胡同,说明前进方向已无路可走,则返回一步,继续尝试其它方向是否还有路可走,如果有路可走,则沿该方向继续试探新的方向。按此原则不断搜索,直到找到新的出路或从原路返回入口处无解为止。
搜索算法框架一:
int Search(int x)
{
for (int i = 1;i <= 算符种数;i ++)
if (满足条件)
{
保存结果
if (到目的地) 输出解;
else Search(x + 1);
恢复:保存结果之前的状态{
回溯一步}
}
}
递归回溯法算法框架二:
int Search(int x)
{
if (到目的地) 输出解;
else
for (int i = 1;i <= 算符种数;i ++)
if (满足条件)
{
保存结果;
Search(x + 1);
恢复:保存结果之前的状态{
回溯一步}
}
}
搜索本身其实就是一个套路,只要多写几个就就能顺利掌握
以下是上课讲的例题QAQ~
全排列+密码检验
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int used[10],num[10],n;
int ans[4] = {
2,3,1}; //1 -> 1
void chack()
{
for(int i = 0;i < n;i ++)
if(num[i] != ans[i])
return;
cout<<"密码正确"<<'\n';
for(int i = 0;i < n;i ++)
cout<<num[i];
}
void dfs(int x) // 之前选过几个数 deep (bfs)
{
if(x == n) // 不撞南墙不回头
{
chack();
return;
}
for(int i = 1;i <= n;i ++)
if(!used[i])
{
num[x] = i;
used[i] = 1;
dfs(x + 1);
used[i] = 0; //回溯
}
}
int main()
{
cin>>n;
dfs(0);
}
跳马游戏+固定终点+障碍物
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int X[] = {
2,1};
const int Y[] = {
1,2};
int ma[15][15],ans;
bool chack(int x,int y)
{
if(x < 1||x > 7) return false;
if(y < 1||y > 5) return false;
if(ma[x][y] == 1) return false;
return true;
}
void dfs(int x,int y)
{
if(x == 7&&y == 5)
{
ans ++;
return;
}
for(int i = 0;i < 2;i ++)
{
int x1 = x + X[i];
int y1 = y + Y[i];
if(chack(x1,y1))
{
dfs(x1,y1);
}
}
}
int main()
{
ma[3][3] = 1;
dfs(0,0);
cout<<ans;
}
数的划分
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int num[20],cnt;
void out()
{
for(int i = 1;i <= cnt;i ++)
cout<<num[i]<<" ";
puts("");
}
void dfs(int x,int ji)
{
if(x == 0)
{
out();
return;
}
for(int i