1.杭电1026 Ignatius and the Princess I
1.优先队列 按时间优先 时间小的先出队列 可以使英雄更快的救出公主
2.最后输出的时候 采用递归
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
struct points{
int x;//这里的x相对于是坐标轴的x 也就是数组的列
int y;//这里的y相对于是坐标轴的y 也就是数组的行
int count;
friend bool operator<(points a,points b){//优先队列,按时间来 时间小的先出队列
return a.count>b.count;
}
};
char map[100][100];
points flag[100][100];//它的count是map数组的每个地方的时间值,x和y是它上一步的位置
int direction[2][4]={1,0,-1,0,0,1,0,-1};//右,下,左,上
int n,m;
int bfs(int &count){
priority_queue<points> qu;
int tx,ty;
while(!qu.empty()){
qu.pop();
}
points start,tmp;
start.x=0;start.y=0;start.count=0;
qu.push(start);
while(!qu.empty()){
tmp=qu.top();
qu.pop();
if(tmp.x==(m-1)&&tmp.y==(n-1)){//找到出口
count = tmp.count;
return 1;
}
for(int i=0;i<4;i++){//将四个方向
tx=tmp.x+direction[0][i];
ty=tmp.y+direction[1][i];
if(tx<0||ty<0||tx>=m||ty>=n||map[ty][tx]=='X'){
continue;
}
start.x=tx;start.y=ty;start.count=tmp.count+1;
flag[ty][tx]=tmp;
flag[ty][tx].count=0;
if(map[ty][tx]>'0'&& map[ty][tx]<'10') {
start.count+=map[ty][tx]-'0';
flag[ty][tx].count=map[ty][tx]-'0';
}
qu.push(start);
map[ty][tx]='X';//这个格子走过了就封掉,因为如果再走这个格子时间会花更久
}
}
return 0;
}
void display(int count, int x,int y){//输出结果
if(count==0)return;
count-=flag[x][y].count;
display(count-1,flag[x][y].y,flag[x][y].x);
cout<<count++<<"s:("<<flag[x][y].y<<","<<flag[x][y].x<<")->("<<x<<","<<y<<")"<<endl;
while (flag[x][y].count--)
cout << count++ << "s:FIGHT AT (" << x << "," << y << ")" << endl;
}
int main()
{
while(cin>>n>>m){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>map[i][j];
}
}
int count=0;
memset(flag,0,sizeof(flag));
int result=bfs(count);
if(result){
cout<<"It takes "<<count<<" seconds to reach the target position, let me show you the way."<<endl;
display(count,n-1,m-1);
}
else{
cout<<"God please help our poor hero."<<endl;
}
cout<<"FINISH"<<endl;
}
return 0;
}