前面发了很多搜索的题,这里补充一点搜索的资料。。
这里简单说一下(伪代码)
深搜(pascal)
procedure dfs(x:longint)
begin
if x为边界 then 处理;
if 条件可行 then
begin
h[x]=true;//hash标记
dfs(下一个x);
h[x]=false;//回溯
end;
end;
深搜的C++代码就差不多了,就不打了
宽搜(pascal)
var
l,r:longint;//队列指针
q:array[0..MAXN] of longint;//声明一个队列
procedure pushback(x:longint)
begin
inc(r);
q[r]=x;
end;
function popback:longint;
begin
inc(l);
exit(q[l]);
end;
procedure bfs;//广搜
begin
while l<r do//只要队列不为空
begin
x=popback;//出队
kuo(x);//根据题意对x进行扩展
if x没入过队 then
begin
标记x已经入队;
对x进行处理;//比如走迷宫是步数+1
pushback(x);
end;
end;
end;
begin
l=0;r=0;//队列清空
pushback(first);//初始状态入队
bfs;
end.
这里做一个解释 在广搜中的队列约定为左开右闭的区间(l,r],(不要问我为什么,只是为了方便,统一,你自己约定一个其他的也可以,但要考虑其他人是否能看懂,代码的可读性咋样)
如果你看到这没看懂,请继续往下看。。。
C++的代码就很短了,可以直接调用STL
#include<cstdio>//标准输入输出头文件
#include<queue>//队列STL头文件
using namespace std;
queue<int> q;//声明一个队列q
int main()
{
q.push(first);//初始状态入队
while(!q.empty)//只要队不为空
{
x=q.front();//取队首值
q.pop();//弹出队首
对x进行扩展;
if(x没入过队)
{
对x进行处理;//如走迷宫的步数+1等等
q.push(x);
}
}
}
在广搜中一般要记录的不止一个值,如走迷宫要记录横纵坐标x,y和步数step 这个时候往往要用到记录类型,这里以走迷宫的三个参数为例
//pascal
type tnode=record
x,y,step:longint;
end;
//C++
typedef struct {int x,y,step;}tnode;
//声明队列的时候把longint(pascal)或int(C++)改成tnode即可,
//声明用tnode,调用如下
tnode q;
q.x=横坐标;
q.y=纵坐标;
q.step=步数;
以上代码纯粹手打,难免有错,有读者发现的请纠正一下,可以发站内消息,也可以致邮 jiangzh777@163.com 感激不尽