题意:给出一个类似迷宫的地图,求靠左走,靠右走,最短的路径。
思路:dfs+bfs。此题相当的纠结,方向的把握啊,有点小难啊……(方向转换以后在补上吧,这次就不先写了)总之要找到来时的路,然后才能判断左右。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstdlib>
using namespace std;
struct state
{
int x,y;
int step;
} st;
int m,n;
int L,R;
const int maxn=1000;
char map[maxn][maxn];
int dirx[4]= {1,0,-1,0};
int diry[4]= {0,-1,0,1};
int dst=0;
int dir1[4]= {0,1,0,-1};
int dir2[4]= {1,0,-1,0};
int vis[maxn][maxn];
int checkstate(state s)
{
if (vis[s.x][s.y]==0&&s.x<R&&s.y<L&&s.x>=0&&s.y>=0)
return 1;
else
return 0;
}
int dfs(int m,int n,int dir,int p)
{
if (map[m][n]=='E')
{
return 1;
}
if (dir==1)//left
{
for (int i=p; i<=p+3; i++)
{
int temprm=m+dir1[(i+3)%4];
int temprn=n+dir2[(i+3)%4];
if (temprm<R&&temprm>=0&&temprn<L&&temprn>=0&&map[temprm][temprn]!='#')
{
//vis[temprm][temprn]=1;
return 1+dfs(temprm,temprn,dir,(i+3)%4);
//vis[temprm][temprn]=0;
}
}
}
if (dir==2) // right
{
for (int i=p+2; i>=p-1; i--)
{
int templm=m+dir1[(i+3)%4];
int templn=n+dir2[(i+3)%4];
if (map[templm][templn]!='#'&&templm<R&&templm>=0&&templn<L&&templn>=0)
{
//vis[templm][templn]=1;
return 1+dfs(templm,templn,dir,(i+3)%4);
//vis[templm][templn]=0;
}
}
}
}
void bfs()
{
queue <state> q;
state now,next;
st.step=1;
q.push(st);
vis[st.x][st.y]=1;
while (!q.empty())
{
now=q.front();
q.pop();
if (map[now.x][now.y]=='E')
{
cout<<now.step<<endl;
}
for (int i=0; i<4; i++)
{
next.x=now.x+dirx[i];
next.y=now.y+diry[i];
if (checkstate(next))
{
vis[next.x][next.y]=1;
next.step=now.step+1;
q.push(next);
}
}
}
}
int main()
{
int cas;
int dir;
int p;
cin>>cas;
while(cas--)
{
cin>>L>>R;
int dstep=0;
for(int i=0; i<R; i++)
for(int j=0; j<L; j++)
{
cin>>map[i][j];
if(map[i][j]=='#')
vis[i][j]=1;
else
vis[i][j]=0;
if(map[i][j]=='S')
{
m=i;
n=j;
}
}
if(m==0)
p=1;
else if(m==R-1)
p=3;
else if(n==0)
p=2;
else if(n==L-1)
p=0;
cout<<dfs(m,n,1,p)<<" ";
for(int i=0; i<R; i++)
for(int j=0; j<L; j++)
{
if(map[i][j]=='#')
vis[i][j]=1;
else
vis[i][j]=0;
if(map[i][j]=='S')
{
m=i;
n=j;
}
}
cout<<dfs(m,n,2,p)<<" ";
for(int i=0; i<R; i++)
for(int j=0; j<L; j++)
{
if(map[i][j]=='#')
vis[i][j]=1;
else
vis[i][j]=0;
if(map[i][j]=='S')
{
st.x=i;
st.y=j;
}
}
bfs();
}
return 0;
}