当前位置: 首页 > 工具软件 > Goddess > 使用案例 >

Oh,mygoddess

郭知
2023-12-01

算法:bfs+优先队列

描述
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

代码:

 #include <iostream>
  #include <queue>
  #include <string>
  #include <cstring>
  #include <algorithm>
  #include <iomanip>
  #include <stdio.h>
  using namespace std;
  char ch[55][55];
  int a[55][55],n,m,q,p;
  int b[4][2]={0,1,0,-1,1,0,-1,0};
  struct dot
  {
  	int x,y,step;
  	bool friend operator<(dot node ,dot node1)
  	{return node.step>node1.step;}
  };
  int bfs()
  {
  	priority_queue<dot>que;
  	dot loer,cur;
  	cur.x=0;cur.y=0;cur.step=0;
  	memset(a,0,sizeof(a)); 
	a[0][0]=1;
	que.push(cur);
	while(que.size())
	{
		loer=que.top();
		que.pop();
		if(loer.x==p&&loer.y==q) return loer.step;
		for(int i=0;i<4;i++)
		{
			int dx=loer.x+b[i][0];
			int dy=loer.y+b[i][1];
			if(dx>=0&&dx<n&&dy>=0&&dy<m&&!a[dx][dy])
			{
				if(ch[dx][dy]=='O')
				{
					cur.x=dx;cur.y=dy;cur.step=loer.step+1;
					a[dx][dy]=1;
					que.push(cur);
				}
				else if(ch[dx][dy]=='#')
				{
					cur.x=dx;cur.y=dy;cur.step=loer.step+4;
					a[dx][dy]=1;
					que.push(cur);
				}
			}
		}
	}
	return -1;
  }
  int main()
  {
  	int i,j;
  	  while(cin>>n>>m)
  	  {
  	  	   for(i=0;i<n;i++)
  	  	        for(j=0;j<m;j++)
  	  	            cin>>ch[i][j];
  	  	   cin>>p>>q;
  	  	   p--;q--;
  	  	   cout<<bfs()<<endl;
	  }
	  return 0;
  }


 类似资料:

相关阅读

相关文章

相关问答