坦克大战
-
描述
-
Many of us had played the game "Battle city" in our childhood, and some people (like me) even often play it on computer now.
What we are discussing is a simple edition of this game. Given a map that consists of empty spaces, rivers, steel walls and brick walls only. Your task is to get a bonus as soon as possible suppose that no enemies will disturb you (See the following picture).
Your tank can't move through rivers or walls, but it can destroy brick walls by shooting. A brick wall will be turned into empty spaces when you hit it, however, if your shot hit a steel wall, there will be no damage to the wall. In each of your turns, you can choose to move to a neighboring (4 directions, not 8) empty space, or shoot in one of the four directions without a move. The shot will go ahead in that direction, until it go out of the map or hit a wall. If the shot hits a brick wall, the wall will disappear (i.e., in this turn). Well, given the description of a map, the positions of your tank and the target, how many turns will you take at least to arrive there? -
-
解题思路:
-
一看题目我就觉得可以用广搜来做,但是这里要求最少要多少步,于是我就在想在保存队列的时候要是能按步数从小到大的顺序来存就好了,这样每次都是步数最少的先走,那么肯定第一个达到target的就肯定是步数最少的了,但是在想要怎样才能够是队列按升序保存呢?google了一下,发现有种队列叫做优先级队列,于是AC!!!
-
对于优先级队列还不熟悉的可以看看这篇:http://www.cppblog.com/shyli/archive/2007/04/06/21366.html#include<stdio.h> #include<stdlib.h> #include<queue> #define N 305 using namespace std; int n,m,ans; int Map[N][N]; struct node{ friend bool operator< (node n1, node n2)//自己定义优先级操作 { return n1.step>n2.step; } int x; int y; int step; }; int next[4][2]={ {1,0},{0,1},{-1,0},{0,-1} }; node start; void bfs(node start) { priority_queue <node> q;//优先级队列 node temp,cur; int x,y; int i; while(!q.empty()) q.pop(); q.push(start); while(!q.empty()){ cur=q.top(); q.pop(); for(i=0;i<4;i++){ x=cur.x+next[i][0]; y=cur.y+next[i][1]; if(x>=0&&x<=n&&y>=0&&y<=m&&Map[x][y]){ if(Map[x][y]==3){ ans=cur.step+1; return ; } else{ temp.x=x; temp.y=y; temp.step=cur.step+Map[x][y]; q.push(temp); Map[x][y]=0; } } } } } int main() { char temp; int i,j; while(scanf("%d%d",&n,&m)&&(m+n)!=0){ getchar(); for(i=0;i<n;i++){ for(j=0;j<m;j++) { scanf("%c",&temp); switch(temp){ case 'Y':start.x=i,start.y=j,start.step=0,Map[i][j]=0;break; case 'E':Map[i][j]=1;break; case 'B':Map[i][j]=2;break; case 'T':Map[i][j]=3;break; default :Map[i][j]=0 ;break; } } getchar(); } ans=-1; bfs(start); printf("%d\n",ans); } }
-
-
-
-