Nyoj 82 迷宫寻宝(一)

来源:互联网 发布:日程本 知乎 编辑:程序博客网 时间:2024/06/05 12:46

题目来源:http://acm.nyist.net/JudgeOnline/problem.php?pid=82

#include <iostream>#include <cstring>#include <cstdio>#include <queue>using namespace std;const int MAXN = 25;struct Point_Pos{int x;int y;Point_Pos(){x = 0;y = 0;}};Point_Pos TargetPos, DoorPos[5];//宝藏的位置,每个门的位置char Graph[MAXN][MAXN];//储存藏宝图int keynum[5];//每个门的钥匙的数量bool doornum[5];//看A~E是否都存在int row, col;//行, 列int dir[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};bool Is_CanGo(Point_Pos t)//判断该位置是否可行{if(t.x < 0 || t.x >= row || t.y < 0 || t.y >= col || Graph[t.x][t.y] == 'X')return false;return true;}bool Check_Key()//查看所有钥匙是否用完{for(int i = 0; i < 5; ++i){if(keynum[i] > 0)return false;}return true;}bool BFS(Point_Pos t)//此处记得要用StL, 因为不知道数组要开多大{//Point_Pos Que[400];queue <Point_Pos> Que;//int qe, qs;//qe = qs = 0;//Que[qe++] = t;Que.push(t);while (!Que.empty()){Point_Pos CurPos = Que.front();Que.pop();if(Graph[CurPos.x][CurPos.y] >= 'a' && Graph[CurPos.x][CurPos.y] <= 'e' && keynum[ Graph[CurPos.x][CurPos.y] - 'a'] > 0 ){keynum[ Graph[CurPos.x][CurPos.y] - 'a']--;if(!keynum[ Graph[CurPos.x][CurPos.y] - 'a' ] && doornum[ Graph[CurPos.x][CurPos.y] - 'a' ]){Point_Pos temp;temp.x = DoorPos[Graph[CurPos.x][CurPos.y] - 'a'].x;temp.y = DoorPos[Graph[CurPos.x][CurPos.y] - 'a'].y;if(Graph[temp.x][temp.y] == 'X')//表示之前已经到这个位置,但是没有足够的钥匙,现在满足条件了,可以把这个位置入队了Que.push( temp );//如果不满足条件,不用入队,下面有判断}}if(Graph[CurPos.x][CurPos.y] >= 'A' && Graph[CurPos.x][CurPos.y] <= 'E')//当前钥匙打不开此门,因此把这个位置设置为墙{if(keynum[Graph[CurPos.x][CurPos.y] - 'A'] > 0){Graph[CurPos.x][CurPos.y] = 'X'; continue ;}}Graph[CurPos.x][CurPos.y] = 'X';//走过的位置设置为墙if(CurPos.x == TargetPos.x && CurPos.y == TargetPos.y && Check_Key())//到达目标状态即宝藏位置return true;for(int i = 0; i < 4; ++i){Point_Pos temp;temp.x = CurPos.x + dir[i][0];temp.y = CurPos.y + dir[i][1];if(Is_CanGo(temp))Que.push( temp );}}return false;}int main(){Point_Pos StartPos;int i, j;while(scanf("%d %d", &row, &col) && (row + col)){memset(doornum, false, sizeof(doornum));memset(keynum, 0, sizeof(keynum));for(i = 0; i < 5; ++i)DoorPos[i].x = -1, DoorPos[i].y = -1;for(i = 0; i < row; ++i){scanf("%s", Graph[i]);for(j = 0; j < col; ++j){if(Graph[i][j] == 'G')TargetPos.x = i, TargetPos.y = j;else if(Graph[i][j] == 'S')StartPos.x = i, StartPos.y = j;else if(Graph[i][j] >= 'a' && Graph[i][j] <= 'e')keynum[Graph[i][j] - 'a']++;else if(Graph[i][j] >= 'A' && Graph[i][j] <= 'E'){doornum[ Graph[i][j] - 'A' ] = true;DoorPos[ Graph[i][j] - 'A' ].x = i;DoorPos[ Graph[i][j] - 'A' ].y = j;}}}bool flag = BFS(StartPos);if(flag)printf("YES\n");elseprintf("NO\n");}return 0;}


0 0
原创粉丝点击