如何选择DFS 或 BFS?
- 如果要遍历所有状态,BFS与DFS的效率相当,但DFS实现起来较为简单。偏向用DFS.
- 如果遍历规模较小,采用DFS
- 如果递归次数 > 10万,可能会爆炸,导致runtime error。所以遍历规模较大时,采用BFS。
深搜:使用递归回溯,注意确定循环结束条件和循环次数,每次循环结束后是否取消标记。
如果取消,则会重新遍历——需要得到最优路径,类似Sicily 1152简单马周游和1150魔板DFS
不取消——适用于仅保留遍历的结果,不保留遍历跟踪路径,类似Sicily 1024 求走最远的距离
取消标记
void dfs(int count, Position now)
{
int i,j;
Position next(0,0);
if(finished == 1){
//cout << "finished: " << "第" <<count <<"步:走"<< getN(now) << endl;
return;
}
if(count == 30){
//cout << "set finished true at " << "第" <<count <<"步:走"<< getN(now) << endl;
finished=1;
for(i=0; i<29; i++){
cout << path[i] << " ";
}
cout << path[i] << endl;
}
else{
for(j=0; j<8; j++){
next.x = now.x + dir[i].x;
next.y = now.y + dir[i].y;
//if(getN(next) == 4)
// cout << "又回到了起点" <<endl;
if(next.x>=0 && next.x<=4 && next.y>=0 && next.y<=5 && visited[getN(next)]== 0){
path[count] = getN(next);
visited[getN(next)] = 1;
count++;
dfs(count, next);
visited[getN(next)] = 0;
count--;
}
}
}
}
不取消标记:
void dfs(int start, int dist)
{
int i,next,len;
visited[start] = true;
if(dist > result)
result = dist;
for(i=0; i<path[start].size(); i++){
next = path[start][i].to;
len = path[start][i].length;
if(!visited[path[start][i].to])
dfs(next, dist+len);
}
}
广搜:一层层遍历,如果第一个可行解即是最优解,那么用BFS是最适合的。不需要用到递归。
用到的数据结构是队列:插入元素从后面插入,从队列头取元素,再遍历下一层。
BFS
void bfs(int n)
{
int i;
Node temp(0,0,""), next(0,0,"");
while(true){
temp = path.front();
path.pop_front();
if(temp.op.size() >= n){
cout << -1 << endl;
return;
}
for(i=0; i<3; i++){
if(i==0)
next=doA(temp);
else if(i==1)
next=doB(temp);
else
next = doC(temp);
if(next.x==target.x && next.y == target.y){
cout << next.op.size() << " " << next.op << endl;
return;
}
path.push_back(next);
}
}
}
Sicily1151 + 1515 魔板(BFS+康托展开)
void bfs(int n)
{
int i;
Node temp(0,0,""), next(0,0,"");
while(true){
temp = path.front();
path.pop_front();
if(temp.op.size() >= n){
cout << -1 << endl;
return;
}
for(i=0; i<3; i++){
if(i==0)
next=doA(temp);
else if(i==1)
next=doB(temp);
else
next = doC(temp);
if(next.x==target.x && next.y == target.y){
cout << next.op.size() << " " << next.op << endl;
return;
}
if(!visited[cantor(next.x*10000+next.y)]){
visited[cantor(next.x*10000+next.y)] = true;
path.push_back(next);
}
}
}
}