本题用到了了搜索和队列,第一次将这两个加起来写,有点吃力。。。。。。
队列相关知识:http://blog.csdn.net/zxy_snow/article/details/6118988
#include<stdio.h> #include<string.h> #include<queue> #include<algorithm> using namespace std; int map[220][220]; int a_x,a_y,b_x,b_y,n,m; int top[4][2]={{0,-1},{0,1},{1,0},{-1,0}}; //上下搜索的四个点 struct node{//自定义的队列 int x; int y; int step; friend bool operator < (node n1,node n2){ return n2.step < n1.step; } }; int judge(int x,int y){//判断执行条件 if(x < 0 || x >= n || y < 0 || y >= m) return 1; if(map[x][y] == 1) return 1; return 0; } int bfs(){//搜索 priority_queue<node>q; node cur,next; int i; cur.x = b_x; cur.y = b_y; cur.step = 0; map[cur.x][cur.y] = 1; q.push(cur); while(!q.empty()){ cur = q.top(); q.pop(); if(cur.x == a_x && cur.y == a_y) return cur.step; for(i = 0;i < 4;i++){ next.x = cur.x + top[i][0]; next.y = cur.y + top[i][1]; if(judge(next.x,next.y)) continue; if(map[next.x][next.y] == -1) next.step = cur.step + 2; else next.step = cur.step + 1; map[next.x][next.y] = 1; q.push(next); } } return -1; } int main(){ int i,j,k,t; char str[220]; while(~scanf("%d %d",&n,&m)){ memset(map,0,sizeof(map)); for(i=0;i<n;i++){ scanf("%s",str); for(j=0;str[j];j++){ if(str[j] == 'a'){//标记带搜索的位置 a_x = i; a_y = j; } else if(str[j] == 'r'){//标记开始搜索的位置 b_x = i; b_y = j; } else if(str[j] == '#') map[i][j] = 1;//将为墙的标记为1 else if(str[j] == '.') map[i][j] = 0;//将为道路的标记为0 else if(str[j] == 'x') map[i][j] = -1;//将为敌人的标记为-1 } } int ans = bfs(); if(ans == -1) printf("Poor ANGEL has to stay in the prison all his life.\n"); else printf("%d\n",ans); } return 0; }