链接:click here~~
题意:

3 4 YBEB EERE SSTE 0 0
8
广搜(BFS)+优先队列,从下午4:00多写到现在,用了三种方法,逐渐算是熟悉了这类题的写法,广搜写的有点感觉,继续保持!
【解题思路】广搜+优先队列,枚举所有方向,注意有个耗时的差异,因此很容易想到优先队列 (priority_queue ),也可以用深搜试一下
代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
const int MAX = 305;
char map[MAX][MAX];
int n,m,u,v,s,e;
struct Node
{
int x,y,step;
friend bool operator < (const Node a,const Node b)
{
return a.step > b.step;
}
};
int dir[4][3]= {{1,0},{0,1},{-1,0},{0,-1}};
bool judg(Node temp)
{
int x = temp.x;
int y = temp.y;
if(x<0||x>=n||y<0||y>=m||map[x][y]=='S'||map[x][y]=='R')
return false;
return true;
}
Node pre,last;
int BFS()
{
priority_queue <Node>Q;
Node temp;
Q.push(pre);
while(!Q.empty())
{
pre=Q.top();
Q.pop();
if((pre.x==last.x)&&(pre.y==last.y)) return pre.step;
for(int i = 0; i < 4; i++)
{
temp.x = pre.x + dir[i][0];
temp.y = pre.y + dir[i][1];
temp. step = pre.step + 1;
if(judg(temp))
{
if(map[temp.x][temp.y]=='B')
temp.step += 1;
map[temp.x][temp.y] = 'S';
Q.push(temp);
}
}
}
return -1;
}
void init()
{
for(int i = 0; i < n; i++)
scanf("%s",map[i]);
for(int i = 0; i< n; i++)
for(int j = 0; j < m; j++)
{
if(map[i][j] == 'Y')
{
pre.x = i;
pre.y = j;
pre.step=0;
}
if(map[i][j] == 'T')
{
last.x = i;
last.y = j;
last.step=0;
}
}
}
int main()
{
while(scanf("%d%d",&n,&m),(n||m))
{
init();
int dist = BFS();
printf("%d\n",dist);
}
return 0;
}
NYOJ 284 坦克大战 && POJ 2312 Battle City (广搜+优先队列)
原文:http://blog.csdn.net/u013050857/article/details/44498163