Oh, my goddess
-
描述
-
Shining Knight is the embodiment of justice and he has a very sharp sword can even cleavewall. Many bad guys are dead on his sword.
One day, two evil sorcerer cgangee and Jackchess decided to give him some colorto see. So they kidnapped Shining Knight's beloved girl--Miss Ice! They built a M x Nmaze with magic and shut her up in it.
Shining Knight arrives at the maze entrance immediately. He can reach any adjacent emptysquare of four directions -- up, down, left, and right in 1 second. Or cleave one adjacent wall in 3
seconds, namely,turn it into empty square. It's the time to save his goddess! Notice: ShiningKnight won't leave the maze before he find Miss Ice.
-
输入
-
The input consists of blocks of lines. There is a blank line between two blocks.
The first line of each block contains two positive integers M <= 50 and N <= 50separated by one space. In each of the next M lines there is a string of length N contentsO and #.
O represents empty squares. # means a wall.
At last, the location of Miss Ice, ( x, y ). 1 <= x <= M, 1 <= y <= N.
(Shining Knight always starts at coordinate ( 1, 1 ). Both Shining and Ice's locationguarantee not to be a wall.)
输出
- The least amount of time Shining Knight takes to save hisgoddess in one line. 样例输入
-
3 5 O#### ##### #O#O# 3 4
样例输出
-
14
-
The input consists of blocks of lines. There is a blank line between two blocks.
这个题是个最基本的优先队列+bfs 的模板题,但是由于自己的马虎,错了十几遍也没找到问题出在哪,最后一个字符一个字符的查找,才发现自己犯了一个最低级的错误:优先队列没有返回值,哈哈,好几天没用优先队列,连最基本的格式都忘掉了.也是够了!
优先队列适合处理这种题目,因为下一步可能造成耗费的时间不一样,为了最优解,那么每次都先操作耗费时间最少的,最终的解决才会是最优的,使用优先队列,很方便的优化了这个求解最优解的过程....
虽然只贴上了一篇代码,但是实际错了n 次,来回改来改去.......
留个图片,铭记:
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
char map[55][55];
int vis[55][55],dx[4]={-1,0,0,1},dy[4]={0,-1,1,0};
int n,m,ex,ey;
struct migong
{
int x,y;
int time;
friend bool operator < (migong a,migong b)
{
return a.time>b.time;
}
};
void slove()
{
memset(vis,0,sizeof(vis));
priority_queue<migong> q;
migong st={1,1,0};
q.push(st);vis[1][1]=1;
while(!q.empty())
{
st=q.top();q.pop();
if(st.x==ex&&st.y==ey)
{
printf("%d\n",st.time);
return;
}
for(int i=0;i<4;++i)
{
int tx=st.x+dx[i],ty=st.y+dy[i];
if(tx<1||tx>n||ty<1||ty>m)
{
continue;
}
if(!vis[tx][ty])
{
int tt=st.time+1;
if(map[tx][ty]=='#')
{
tt+=3;
}
migong tp={tx,ty,tt};
vis[tx][ty]=1;
q.push(tp);
}
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;++i)
{
getchar();
for(int j=1;j<=m;++j)
{
char y;
scanf("%c",&y);
map[i][j]=y;
}
}
scanf("%d%d",&ex,&ey);
slove();
}
return 0;
}
认真,仔细,别马虎,不知道告诉了自己多少遍,还是这么不经心,早晚都要栽在细节上,一定要细心,尽力...