Description
Given a city map with E (1 <= E <= 40) east/west street locations and N (1 <= N <= 30) north/south street locations, create instructions for a taxi driver to navigate from the start of his route (marked 'S') to the end (marked 'E'). Each instruction is a direction (one of 'N', 'E', 'S', or 'W') followed by a space followed by an integer that tells how many blocks to drive in that direction. If multiple routes are available, your program should output the shortest route. The shortest route is guaranteed to exist and be unique.
The map is depicted as a grid of '+'s that represent intersections and a set of roads depicted as '-' and '|'. Buildings and other obstacles are shown as '.'s. Here is a typical map:
+-+-+.+-+-+
|...|.....|
+-+.+-+-+-+
..|.......|
S-+-+-+.E-+
The taxi should go east, north, west, north, east two blocks, and so on. See the output format and sample solution below for its complete route.
Input
* Lines 2..2*N: These lines each contain 2*E-1 characters and encode the map of the street. Every other input line gives the data for the east/west streets; the remaining lines show the north/south streets. The format should be clear from the example.
第1行:两个用空格隔开的整数N和E.
第2到2N行:每行有2E-I个字符,表示地图.
Output
Sample Input
3 6
+-+-+.+-+-+
|...|.....|
+-+.+-+-+-+
..|.......|
S-+-+-+.E-+
Sample Output
E 1
N 1
W 1
N 1
E 2
S 1
E 3
S 1
W 1
直接bfs,然后记录路径就行了……
#include<queue>
#include<cstdio>
#include<iostream>
using namespace std; struct na{
int x,y;
};
const int fx[]={,,,-},fy[]={,,-,};
int n,m;
char map[][];
int cm[][];
char c;
queue <na> q;
void pri(int x,int y){
int k,p;
for(;;){
k=cm[x][y];p=;
if (k==) printf("E ");else
if (k==) printf("S ");else
if (k==) printf("W ");else
printf("N ");
while(cm[x][y]==k){
x+=fx[k];
y+=fy[k];
if (map[x][y]=='+') p++;
}
if (map[x][y]=='E'){
printf("%d",p+);
return;
}
printf("%d\n",p);
}
}
int main(){
scanf("%d%d",&n,&m);
n=n*-;m=m*-;
for (int i=;i<n;i++)
for (int j=;j<m;j++){
c=getchar();
while(c=='\n') c=getchar();
map[i][j]=c;
if (c=='E'){
na tmp;
tmp.x=i;tmp.y=j;
q.push(tmp);
}
cm[i][j]=-;
}
while(!q.empty()){
na k=q.front();q.pop();
for (int i=;i<;i++){
na now=k;
now.x+=fx[i];now.y+=fy[i];
if (now.x<||now.y<||now.x>=n||now.y>=m) continue;
if (map[now.x][now.y]=='.') continue;
if (cm[now.x][now.y]==-){
cm[now.x][now.y]=i>?i-:i+;
if (map[now.x][now.y]=='S'){
pri(now.x,now.y);
return ;
}
q.push(now);
}
}
}
}