http://poj.org/problem?id=3083
好久没练搜索了 找了一道搜索综合题- -
DFS*2+BFS
题目大意:
给定一个迷宫,S是起点,E是终点,#是墙不可走,.可以走
先输出左转优先时,从S到E的步数
再输出右转优先时,从S到E的步数
最后输出S到E的最短步数
由于bfs时候忘了vis,结果- - 超内存了.....
#include <cstdio>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fstream>
#include <math.h>
#include <queue>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 44;
bool maze[maxn][maxn];
int lstep;//左边优先搜索 时从S到E的总步数
int rstep;//右边优先搜索 时从S到E的总步数
int shortstep;//最少总步数
int fl[]={1,0,3,2};
int fr[]={3,0,1,2};
int fx[4]={-1,0,1,0};
int fy[4]={0,-1,0,1};
struct SE
{
int r,c;
};
SE s,e;//起止点
struct point
{
int px;
int py;
int step;
};
/*
0
1 3 <<direction!!!
2
*/
void dfs_l(int x,int y,int d )
{
if (x==e.r&&y==e.c)
{
cout<<lstep<<' ';
return ;
}
lstep++;
int nx,ny;
for(int j=0;j<4;j++)
{
int i=(d+fl[j])%4;
nx=x+fx[i];
ny=y+fy[i];
if(maze[nx][ny]){
dfs_l(nx,ny,i);
return ;
}
}
}
void dfs_r(int x,int y,int d )
{
if (x==e.r&&y==e.c)
{
cout<<rstep<<' ';
return ;
}
rstep++;
int nx,ny;
for(int j=0;j<4;j++)
{
int i=(d+fr[j])%4;
nx=x+fx[i];
ny=y+fy[i];
if(maze[nx][ny]){
dfs_r(nx,ny,i);
return ;
}
}
}
void bfs(int x,int y)
{
bool vis[maxn][maxn];
memcpy(vis,maze,sizeof(maze));
queue <point> q;
point now;
now.px=x;
now.py=y;
now.step=1;
vis[x][y]=false;
q.push(now);
while(!q.empty())
{
point next;
now=q.front();
q.pop();
if (now.px==e.r&&now.py==e.c)
{
cout<<now.step<<endl;
while(!q.empty())
q.pop();
return ;
}
for(int i=0;i<4;i++)
{
next.px=now.px+fx[i];
next.py=now.py+fy[i];
next.step=now.step+1;
if (maze[next.px][next.py]&&vis[next.px][next.py]){
q.push(next);vis[next.px][next.py]=false;
}
}
}
}
int main()
{
//freopen ("input.txt","r",stdin);
int test;
cin>>test;
while(test--)
{
int direction; //S的初始方向
int w,h;
cin>>w>>h;
/*Initial*/
lstep=1,rstep=1;
memset(maze,false ,sizeof(maze));
for(int i=1;i<=h;i++)
for(int j=1;j<=w;j++)
{
char c;
cin>>c;
if(c=='.')
maze[i][j]=true;
else if(c=='S')
{
s.r=i;
s.c=j;
maze[i][j]=true;
if(i==h) direction=0;
else if(i==1) direction=2;
else if(j==1) direction=3;
else if(j==w)direction=1;
}
else if(c=='E')
{
e.r=i;
e.c=j;
maze[i][j]=true;
}
else {
maze[i][j]=false;
}
}
dfs_l(s.r,s.c,direction);
dfs_r(s.r,s.c,direction);
bfs (s.r,s.c);
}
return 0;
}