5 6 .XX.1. ..X.2. 2...X. ...XX. XXXXX. 5 6 .XX.1. ..X.2. 2...X. ...XX. XXXXX1 5 6 .XX... ..XX1. 2...X. ...XX. XXXXX.
It takes 13 seconds to reach the target position, let me show you the way. 1s:(0,0)->(1,0) 2s:(1,0)->(1,1) 3s:(1,1)->(2,1) 4s:(2,1)->(2,2) 5s:(2,2)->(2,3) 6s:(2,3)->(1,3) 7s:(1,3)->(1,4) 8s:FIGHT AT (1,4) 9s:FIGHT AT (1,4) 10s:(1,4)->(1,5) 11s:(1,5)->(2,5) 12s:(2,5)->(3,5) 13s:(3,5)->(4,5) FINISH It takes 14 seconds to reach the target position, let me show you the way. 1s:(0,0)->(1,0) 2s:(1,0)->(1,1) 3s:(1,1)->(2,1) 4s:(2,1)->(2,2) 5s:(2,2)->(2,3) 6s:(2,3)->(1,3) 7s:(1,3)->(1,4) 8s:FIGHT AT (1,4) 9s:FIGHT AT (1,4) 10s:(1,4)->(1,5) 11s:(1,5)->(2,5) 12s:(2,5)->(3,5) 13s:(3,5)->(4,5) 14s:FIGHT AT (4,5) FINISH God please help our poor hero. FINISH
简单的BFS与HDU1175相似。 在Search函数中,如果我把t1变量的定义放在while循环中,就会超时。个人理解当把t1放在while循环中定义,每一次循环都会重新定义t1,重新给t1分配内存。放在while循环中即使不超时,这么搞内存也受不了呀!
#include<stdio.h> #include<iostream> #include<queue> using namespace std; int N,M; char map[110][110]; int ex,ey; int result; int flag[110][110]; int dir[4][2]={{-1,0},{0,-1},{1,0},{0,1}}; struct point{ int x,y; int time; }; bool check(int x,int y){ if(x>=0&&y>=0&&x<N&&y<M)return true; return false; } int Search(int sx,int sy){ point t1,t2; queue<point> Q; t1.x=sx; t1.y=sy; t1.time=0; flag[0][0]=0; Q.push(t1); while(!Q.empty()){ t1=Q.front(); if(t1.x==N-1&&t1.y==M-1){ if(result>t1.time)result=t1.time; } Q.pop(); for(int i=0;i<4;i++){ int dx=t1.x+dir[i][0]; int dy=t1.y+dir[i][1]; if(check(dx,dy)&&map[dx][dy]=='.'){ t2.x=dx; t2.y=dy; t2.time=t1.time+1; if(t2.time<flag[t2.x][t2.y]&&t2.time<=result){ flag[t2.x][t2.y]=t2.time; Q.push(t2); } } else if(check(dx,dy)&& (map[dx][dy]>='1' && map[dx][dy]<='9')){ t2.x=dx; t2.y=dy; t2.time=t1.time+1+map[dx][dy]-'0'; if(t2.time<flag[t2.x][t2.y]&&t2.time<=result){ flag[t2.x][t2.y]=t2.time; Q.push(t2); } } } } return result; } void print(int x,int y,int step){ if(step==0)return; int time=0,i; int dx,dy,rx,ry; if(map[x][y]>='1' && map[x][y]<='9'){ time=map[x][y]-'0'; } for(i=0;i<4;i++){ dx = x+dir[i][0]; dy = y+dir[i][1]; if(check(dx,dy)){ int t=0; if(map[x][y]>='1' && map[x][y]<='9')t=map[x][y]-'0'; if(flag[dx][dy]+1+t==flag[x][y]){ rx=dx; ry=dy; print(dx,dy,step-time-1); break; } } } printf("%ds:(%d,%d)->(%d,%d)\n",step-time,rx,ry,x,y); while(time>0){ printf("%ds:FIGHT AT (%d,%d)\n",step-time+1,x,y); time--; } return ; } int main(){ int i,j; while(scanf("%d%d",&N,&M)!=EOF){ for(i=0;i<110;i++) for(j=0;j<110;j++) flag[i][j]=99999; for(i=0;i<N;i++){ scanf("%s",map[i]); } result=99999; int t=Search(0,0); if(t==99999){ printf("God please help our poor hero.\nFINISH\n"); } else{ printf("It takes %d seconds to reach the target position, let me show you the way.\n",t); print(N-1,M-1,t); printf("FINISH\n"); } } return 0; }