标签:
n*m的图,其中有
‘.’:空地
‘X‘:墙
’S‘:起点
‘D‘:终点
’1‘-’9‘:表示该点有多少炸弹,炸弹可以炸墙
n,m范围只有8
优先队列里直接把当前的状态图压入,判断墙是否还存在,每个点可以走到多次
#include "stdio.h" #include "string.h" #include "queue" using namespace std; const int dir[4][2]={ {1,0},{-1,0},{0,1},{0,-1} }; char str[10][10]; int used[10][10][50]; int n,m,s_x,s_y,e_x,e_y; struct node { int x,y,e,t; char mp[10][10]; friend bool operator<(node a,node b) { return b.t<a.t; } }; int bfs() { priority_queue<node>q; node cur,next; int i,j; cur.x=s_x; cur.y=s_y; cur.e=0; cur.t=0; for (i=0;i<n;i++) for (j=0;j<m;j++) cur.mp[i][j]=str[i][j]; memset(used,0,sizeof(used)); used[s_x][s_y][0]=1; q.push(cur); while(!q.empty()) { cur=q.top(); q.pop(); if (cur.x==e_x && cur.y==e_y) return cur.t; for (i=0;i<4;i++) { next=cur; next.x+=dir[i][0]; next.y+=dir[i][1]; next.t++; if (next.x<0 || next.x>=n || next.y<0 || next.y>=m) continue; if (next.mp[next.x][next.y]=='.' && used[next.x][next.y][next.e]<10) { used[next.x][next.y][next.e]++; q.push(next); } if (next.mp[next.x][next.y]=='X' && next.e!=0 && used[next.x][next.y][next.e-1]<10) { next.e--; next.t++; next.mp[next.x][next.y]='.'; q.push(next); used[next.x][next.y][next.e]++; } if (next.mp[next.x][next.y]<='9' && next.mp[next.x][next.y]>='1' && used[next.x][next.y][next.e+1]<10) { next.e+=next.mp[next.x][next.y]-'0'; next.mp[next.x][next.y]='.'; q.push(next); used[next.x][next.y][next.e]++; } } } return -1; } int main() { int i,j; while (scanf("%d%d",&n,&m)!=EOF) { if (n+m==0) break; for (i=0;i<n;i++) scanf("%s",str[i]); for (i=0;i<n;i++) for (j=0;j<m;j++) if (str[i][j]=='S') { s_x=i; s_y=j; str[i][j]='.'; } else if (str[i][j]=='D') { e_x=i; e_y=j; str[i][j]='.'; } printf("%d\n",bfs()); } return 0; }
标签:
原文地址:http://blog.csdn.net/u011932355/article/details/45484367