POJ 2312 Battle City 【SPFA最短路详解】

Battle City
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 9444   Accepted: 3121

Description

Many of us had played the game "Battle city" in our childhood, and some people (like me) even often play it on computer now. 

What we are discussing is a simple edition of this game. Given a map that consists of empty spaces, rivers, steel walls and brick walls only. Your task is to get a bonus as soon as possible suppose that no enemies will disturb you (See the following picture). 

Your tank can't move through rivers or walls, but it can destroy brick walls by shooting. A brick wall will be turned into empty spaces when you hit it, however, if your shot hit a steel wall, there will be no damage to the wall. In each of your turns, you can choose to move to a neighboring (4 directions, not 8) empty space, or shoot in one of the four directions without a move. The shot will go ahead in that direction, until it go out of the map or hit a wall. If the shot hits a brick wall, the wall will disappear (i.e., in this turn). Well, given the description of a map, the positions of your tank and the target, how many turns will you take at least to arrive there?

Input

The input consists of several test cases. The first line of each test case contains two integers M and N (2 <= M, N <= 300). Each of the following M lines contains N uppercase letters, each of which is one of 'Y' (you), 'T' (target), 'S' (steel wall), 'B' (brick wall), 'R' (river) and 'E' (empty space). Both 'Y' and 'T' appear only once. A test case of M = N = 0 indicates the end of input, and should not be processed.

Output

For each test case, please output the turns you take at least in a separate line. If you can't arrive at the target, output "-1" instead.

Sample Input

3 4
YBEB
EERE
SSTE
0 0

Sample Output

8

题目描述:给你一个mxn的字符矩阵,S和R是墙和河的意思,都走不过去。B是需要两步才能走过去,E就是空地,需要一步可以走过去。Y是起点,T是终点。问从起点到终点的最少步数。

思路:直接SPFA求最短路,在bfs的时候对当前结点判断一下,S和R不进队,B的权值是2,E的权值是1.开一个二维的inq数组判断一下当前点是否在队里。

#include
#include
#include
#include
#include
using namespace std;
int n,m,inq[400][400];
int sx,sy,ex,ey;
char map[400][400];
int d[400][400],nx[4]={0,1,0,-1},ny[4]={1,0,-1,0};
typedef pair P;
queue

Q; void SPFA() { int i,j; d[sx][sy]=0; Q.push(P(sx,sy)); inq[sx][sy]=1; while(Q.size()) { P t=Q.front(); Q.pop(); inq[t.first][t.second]=0; int x,y; for(int i=0;i<4;i++) { x=t.first+nx[i]; y=t.second+ny[i]; if(x>=0&&x=0&&yd[t.first][t.second]+v) { d[x][y]=d[t.first][t.second]+v; if(inq[x][y]==1) continue; else { Q.push(P(x,y)); inq[x][y]=1; } } } } } } void init() { memset(inq,0,sizeof(inq)); memset(map,0,sizeof(map)); int i,j; for(i=0;i<400;i++) { for(j=0;j<400;j++) d[i][j]=1e9+7; } while(Q.size()) Q.pop(); } int main() { int i,j; while(cin>>n>>m) { if(n==m&&n==0) break; init(); for(i=0;i>map[i][j]; if(map[i][j]=='Y') { sx=i; sy=j; } if(map[i][j]=='T') { ex=i; ey=j; } } SPFA(); if(d[ex][ey]!=1e9+7) cout<



你可能感兴趣的:(ACM_最短路)