飞越原野 (经典广搜)
飞越原野
Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 60 Accepted Submission(s) : 16
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
Input
Output
Sample Input
1 4 4 2 PLLP PPLP PPPP PLLP
Sample Output
5
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
//#include<windows.h>
using namespace std;
#define maxn 110
typedef struct Node
{
int x,y;
int step;
int dist;
}Node;
int n,m,D;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int step[maxn][maxn],dist[maxn][maxn];
char map[maxn][maxn];
int cango(Node next)
{
if(next.x<1||next.x>n) return 0;
if(next.y<1||next.y>m) return 0;
////if(map[next.x][next.y]=='L') return 0;/////害死人了
return 1;
}
int bfs()
{
int i,j;
Node tmp,next;
memset(step,0,sizeof(step)); memset(dist,0,sizeof(dist));
tmp.x=1,tmp.y=1,tmp.dist=D,tmp.step=0,dist[1][1]=D,step[1][1]=0;
queue<Node>Q;
Q.push(tmp);
while(!Q.empty())
{
Node tmp;
tmp=Q.front(),Q.pop();
for(i=0;i<4;i++)
{
next.x=tmp.x+dx[i],next.y=tmp.y+dy[i];
if(!cango(next)) continue;//////有时候用函数也是有害处的,
if(map[next.x][next.y]!='L')
{
/*找到返回*/
if(next.x==n&&next.y==m) return tmp.step+1;
/*用步走*/
if(step[next.x][next.y]>0)
{
if(tmp.step+1<step[next.x][next.y]||tmp.dist>dist[next.x][next.y])
{
next.step=tmp.step+1; step[next.x][next.y]=tmp.step+1;
next.dist=tmp.dist; dist[next.x][next.y]=tmp.dist;
Q.push(next);
}/*
else if(tmp.dist>next.dist)
{
next.step=tmp.step+1;
next.dist=tmp.dist;
Q.push(next);
}*/
}
else if(dist[next.x][next.y]<D) //防止把原点(1,1,0,D)放进去 ,不加if时把原点放进去了,调试了好久(两个晚上,伤不起);
{
next.step=tmp.step+1; step[next.x][next.y]=tmp.step+1;
next.dist=tmp.dist; dist[next.x][next.y]=tmp.dist;
Q.push(next);
}
}
/*飞行*/
for(j=2;j<=tmp.dist;j++)
{
int d=tmp.dist-j;
next.x=tmp.x+j*dx[i],next.y=tmp.y+j*dy[i];
if(!cango(next)) break;
if(map[next.x][next.y]=='L') continue;
if(next.x==n&&next.y==m) return tmp.step+1;
if(step[next.x][next.y]==0&&dist[next.x][next.y]<D||tmp.step+1<step[next.x][next.y]||d>dist[next.x][next.y])
{
next.step=tmp.step+1; step[next.x][next.y]=tmp.step+1;
next.dist=d; dist[next.x][next.y]=d;
Q.push(next);
}
}
}
}
//printf("ERROR!\n");//////调试
return 0;
}
int main()
{
//freopen("input.txt","r",stdin);
// DWORD take=GetTickCount();
int i,j,T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d\n",&n,&m,&D);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
if(j==m) scanf("%c\n",&map[i][j]);
else scanf("%c",&map[i][j]);
/*
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++) printf("%c",map[i][j]);
printf("\n");
}*/
int t=bfs();
if(t) printf("%d\n",t);
else printf("impossible\n");
}
//printf("%d\n",GetTickCount()-take);
return 0;
}