标签:dijkstra算法 nyoj284 nyoj 284坦克大战

3 4 YBEB EERE SSTE 0 0
8
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
struct node
{
int x,y,step;
friend bool operator <(node a,node b)
{
return a.step>b.step;
}
};
priority_queue<node> s;//结构体优先队列
char map[304][304];
int m,n,visit[304][304],dir[4][2]={1,0,-1,0,0,1,0,-1};//vis标记是否访问,dir代表四个方向
bool limit(int x,int y)//判断是否出界和此刻指向的位置是否是水和石头
{
if(x>=0&&y>=0&&x<m&&y<n&&map[x][y]!='S'&&map[x][y]!='R')
return true;
else
return false;
}
int tonum(char c)//把对应的字母转换为需要的步数
{
if(c=='B')
return 2;
if(c=='E'||c=='T')
return 1;
}
int dfs(int star,int end)
{
node temp,sta;
visit[star][end]=1;//Y位置标记为1
temp.x=star,temp.y=end,temp.step=0;
s.push(temp);
while(!s.empty())//完全是dijkstra思想 看不懂的百度吧
{
int ant;
temp=s.top();
s.pop();
star=temp.x,end=temp.y,ant=temp.step;
for(int i=0;i<4;i++)
{
temp.x+=dir[i][0];
temp.y+=dir[i][1];
if(limit(temp.x,temp.y)&&!visit[temp.x][temp.y])
{
visit[temp.x][temp.y]=1;
temp.step+=tonum(map[temp.x][temp.y]);
if(map[temp.x][temp.y]=='T')
return temp.step;
s.push(temp);
}
temp.x=star,temp.y=end,temp.step=ant;
}
}
return -1;
}
int main()
{
int star_x,star_y;
while(scanf("%d %d",&m,&n)!=EOF&&(m||n))
{
for(int i=0;i<m;i++)
scanf("%s",map[i]);
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(map[i][j]=='Y')
star_x=i,star_y=j;
}
memset(visit,0,sizeof(visit));
printf("%d\n",dfs(star_x,star_y));
while(!s.empty())
s.pop();
memset(map,0,sizeof(map));
}
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
nyoj284 坦克大战(dijkstra(dfs+优先队列))
标签:dijkstra算法 nyoj284 nyoj 284坦克大战
原文地址:http://blog.csdn.net/su20145104009/article/details/46844009