其实蛮喜欢这种题的,但是有的时候需要优化的话总是很恶心。。
BFS即可。这题很顺利。。。不过忘记清空队列了,WA了一次 = =。。
结构体里存X,Y坐标,当前hp还有步数。
如果走过一个点就把hp存下,下次走这个点时候,如果当前hp比存的大,就放入队列,否则,就不放,因为如果加入队列,扩展的方向神马的都一样,但是hp不一样,肯定hp大的更有可能到达目标。
蛮喜欢搜索的现在~~
#include <cstdio> #include <cstdlib> #include <iostream> #include <string.h> #include <queue> #include <limits.h> using namespace std; typedef struct ANT{ int x,y; int hp,step; }ANT; int map[10][10]; int h[10][10]; int dir[8] = {1,0,-1,0,0,1,0,-1}; int n,m; queue<ANT> q; int BFS() { int x,y,hp,step,i,a,b; while( !q.empty() ) { ANT tmp = q.front(); q.pop(); x = tmp.x; y = tmp.y; hp = tmp.hp; step = tmp.step; if( hp == 0 ) continue; for(i=0; i<8; i+=2) { a = x + dir[i]; b = y + dir[i+1]; if( a>=0 && a<n && b>=0 && b<m && map[a][b] != 0 && hp-1 > h[a][b] ) { if( map[a][b] == 3 ) return step+1; if( map[a][b] == 4 ) { tmp.x = a; tmp.y = b; tmp.hp = 6; h[a][b] = 6; tmp.step = step+1; q.push(tmp); } if( map[a][b] == 1 ) { tmp.x = a; tmp.y = b; tmp.hp = hp-1; tmp.step = step+1; h[a][b] = hp-1; q.push(tmp); } } } } return -1; } int main() { int i,k,ans; int sx,sy; while( ~scanf("%d%d",&m,&n) && m && n ) { memset(h,0,sizeof(h)); while( !q.empty() ) q.pop(); for(i=0; i<n; i++) for(k=0; k<m; k++) { scanf("%d",&map[i][k]); if( map[i][k] == 2 ) { ANT tmp; tmp.x = i; tmp.y = k; tmp.hp = 6; h[i][k] = 6; tmp.step = 0; q.push(tmp); } } ans = BFS(); printf("%d/n",ans); } return 0; }