链接:http://acm.hdu.edu.cn/showproblem.php?pid=2579
广搜,只不过可以往回走,所以标记数组也从二维数组变成三维数组。
Ac code:
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int r,c,k;
#define N 105
bool step[N][N][12];
char Maze[N][N];
struct Node
{
int x,y,step;
};
Node start,End;
int d[4][2]={-1,0,1,0,0,1,0,-1};
int BFS();
bool IsValid(int x,int y,int s);
int main()
{
int test,i,j,rs;
cin>>test;
while (test--)
{
memset(step,0,sizeof(step));
memset(Maze,0,sizeof(Maze));
cin>>r>>c>>k;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
cin>>Maze[i][j];
if(Maze[i][j]=='Y') { start.x=i; start.y=j;start.step=0;}
if(Maze[i][j]=='G') { End.x=i; End.y=j;}
}
rs=BFS();
if(rs) cout<<rs<<endl;
else cout<<"Please give me another chance!"<<endl;
}
}
bool IsValid(int x,int y,int s)
{
if(x<0||x>=r||y<0||y>=c) return false;
if(Maze[x][y]=='#'&&s%k!=0) return false;
return true;
}
int BFS()
{
queue<Node> Q;
Q.push(start);
Node temp,t;
int dx,dy,i,s;
while (!Q.empty())
{
temp=Q.front();
Q.pop();
if(temp.x==End.x&&temp.y==End.y) return temp.step;
for(i=0;i<4;i++)
{
dx=temp.x+d[i][0];
dy=temp.y+d[i][1];
s=temp.step+1;
if(IsValid(dx,dy,s)&&!step[dx][dy][s%k])
{
t.x=dx; t.y=dy; t.step=s;
Q.push(t);
step[dx][dy][s%k]=1;
}
}
}
return 0;
}