BFS搜索,重点提到了STL优先队列 priority_queue的运用以及写法
参考http://www.cnblogs.com/penseur/archive/2011/02/26/1965550.html
#include<iostream>
#include<cstdio>
#include<cstring>
#include<memory>
#include<queue>
#include<algorithm>
#include<string>
#include<cmath>
using namespace std;
///
#define Maxn 30
char maze[Maxn][Maxn];
int M, N;
int dir[4][2] = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} };
int mark[Maxn][Maxn][4][5];
struct node
{
int x, y, step, color, dir;
friend bool operator <(node a,node b)
{
return a.step>b.step;
};
};
node start, temp, later, target;
void bfs()
{
int i, j;
priority_queue<node> q;
start.step = start.color = start.dir = 0;
q.push(start);
mark[start.y][start.x][0][0] = true;
while (!q.empty())
{
temp = q.top();
q.pop();
for (i = 0; i < 4; i++)
{
if (temp.dir == i)
{
later.y = temp.y + dir[i][0];
later.x = temp.x + dir[i][1];
later.step = temp.step + 1;
later.color = (temp.color + 1) % 5;
later.dir = temp.dir;
}
else
{
later.y = temp.y;
later.x = temp.x;
if ((int)fabs(temp.dir - i) == 2)
later.step = temp.step + 2;
else
later.step = temp.step + 1;
later.dir = i;
later.color = temp.color;
}
if(!(later.x >=0 && later.x < N && later.y >= 0 && later.y < M && maze[later.y][later.x]!='#'))
continue;
if (!mark[later.y][later.x][later.dir][later.color])
{
if (later.y == target.y && later.x == target.x && later.color == 0)
{
cout<<"minimum time = "<<later.step<<" sec"<<endl;
return;
}
mark[later.y][later.x][later.dir][later.color] = true;
q.push(later);
}
}
}
cout << "destination not reachable" << endl;
}
int main()
{
///
int i, j;
int cases = 0;
while (1)
{
cases++;
cin >> M >> N;
if (M == 0 || N == 0)
break;
if(cases != 1)
cout<<endl;
cout << "Case #" << cases << endl;
memset(mark, false, sizeof(mark));
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
cin >> maze[i][j];
if (maze[i][j] == 'S')
{
start.y = i;
start.x = j;
}
if (maze[i][j] == 'T')
{
target.y = i;
target.x = j;
}
}
}
bfs();
}
///
return 0;
}