题目大体意思就是,求从地图上的Y走到T的最小步数,其中S和R不能走,B要走两步,E要走一步。
测试输入:
3 4
YBEB
EERE
SSTE
0 0
测试输出:
8
这个题要用优先队列,不用的话没有办法保证所求的步数是最小的。
我也查了一些关于优先队列的资料,做以下整理:
在优先队列中,优先级高的元素先出队列。
标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。
优先队列的第一种用法,也是最常用的用法:priority_queue<int> qi;
通过<操作符可知在整数中元素大的优先级高。
第二种方法:
在示例1中,如果我们要把元素从小到大输出怎么办呢?
这时我们可以传入一个比较函数,使用functional.h函数对象作为比较函数。
priority_queue<int, vector<int>, greater<int> >qi2;
第三种方法:
自定义优先级,也就是重载<符号
friend bool operator< (node n1, node n2)
{//<为从大到小排列,>为从小到大排列
return n1.priority > n2.priority;
}
注意:不要重载>,因为标准库默认使用元素类型的<操作来确定他们之间的优先级关系。
#include <stdio.h>
#include <queue>
#include <cstdio>
#include <cstring>
#define SIZE 350
using namespace std;
struct node
{
int x;
int y;
int step;
friend bool operator < (const node &s1,const node &s2)
{
return s1.step > s2.step;
}
};
node start, end;
int m, n;
char map[SIZE][SIZE];
int s[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
priority_queue<node> q;//优先队列
int bfs()
{
int i;
node e;
q.push(start);
map[start.x][start.y] = 'X';
while (!q.empty())
{
e = q.top();
q.pop();
if(e.x == end.x && e.y == end.y)
{
return e.step;
}
for(i = 0; i < 4; i++)
{
int row = e.x + s[i][0];
int sort = e.y + s[i][1];
if(map[row][sort] != 'X' && map[row][sort] != 'S' && map[row][sort] != 'R' && row < m && row >= 0 && sort < n && sort >= 0)
{
node e1;
e1.x = row;
e1.y = sort;
if(map[row][sort] == 'E' || map[row][sort] == 'T')
e1.step = e.step + 1;
else if(map[row][sort] == 'B')
e1.step = e.step + 2;
map[row][sort] = 'X';
q.push(e1);
}
}//for
}//while
return -1;
}
int main (void)
{
int i, j;
while (1)
{
scanf("%d %d", &m, &n);
if(m == 0 && n == 0)
return 0;
while (!q.empty())
{
q.pop();
}
for(i = 0; i < m; i++)
{
getchar();
for(j = 0; j < n; j++)
{
scanf("%c", &map[i][j]);
if(map[i][j] == 'Y')
{
start.x = i;
start.y = j;
start.step = 0;
}
if(map[i][j] == 'T')
{
end.x = i;
end.y = j;
end.step = 0;
// printf("end = %d %d\n", end.x, end.y);
}
}
//getchar();
}
int a = bfs();
printf("%d\n", a);
}
return 0;
}