Different Digits
题目链接:HDU - 1664题意:r*c的迷宫, '*'表示你的位置, '#', 表示墙, '.'表示空地, 'B, Y, R, G'表示门, 'b, y, r, g'表示钥匙,'X'表示出口, 钥匙只能开对应字母的门;
开三维记录状态, vis[x][y][key];
写这个题解只是为了记住, ==的优先级大于&;
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; char G[110][110]; int r, c, s_x, s_y; int vis[110][110][20]; struct node{ int x, y, key, step; }; queue<node> que; int dir[4][2]={0, 1, 1, 0, -1, 0, 0, -1}; void bfs(){ while(!que.empty()) que.pop(); node tmp; tmp.x=s_x, tmp.y=s_y, tmp.key=0, tmp.step=0; que.push(tmp); memset(vis, 0, sizeof(vis)); vis[s_x][s_y][0]=1; while(!que.empty()){ tmp=que.front(); que.pop(); if(G[tmp.x][tmp.y]=='X'){ printf("Escape possible in %d steps.\n", tmp.step); return; } for(int i=0; i<4; i++){ int tx=tmp.x+dir[i][0]; int ty=tmp.y+dir[i][1]; // printf("tmp: %d %d %d %d\n", tmp.x, tmp.y, tmp.key, tmp.step); int tkey=tmp.key; if(tx<0||ty<0||tx>=r||ty>=c||G[tx][ty]=='#') continue; if(G[tx][ty]=='B'){ // printf("B %d %d\n", tx, ty); if((tmp.key&1)==0) continue; } if(G[tx][ty]=='Y'){ //printf("Y %d %d\n", tx, ty); if((tmp.key&(1<<1))==0) continue; } if(G[tx][ty]=='R'){ if((tmp.key&(1<<2))==0) continue; // printf("%d R %d %d %d %d %d\n", tmp.key&(1<<2), tx, ty, tmp.x, tmp.y, tmp.step); } if(G[tx][ty]=='G'){ // printf("G %d %d\n", tx, ty); if((tmp.key&(1<<3))==0) continue; } if(G[tx][ty]=='b'){ // printf("b %d %d\n", tx, ty); tkey=tkey|1; } if(G[tx][ty]=='y'){ //printf("y %d %d\n", tx, ty); tkey=tkey|(1<<1); } if(G[tx][ty]=='r'){ //printf("r %d %d\n", tx, ty); tkey=tkey|(1<<2); } if(G[tx][ty]=='g'){ //printf("g %d %d\n", tx, ty); tkey=tkey|(1<<3); } if(vis[tx][ty][tkey]) continue; //printf("tx:%d ty:%d tkey:%d\n", tx, ty, tkey); node p; p.x=tx, p.y=ty, p.key=tkey, p.step=tmp.step+1; que.push(p); vis[tx][ty][tkey]=1; } } printf("The poor student is trapped!\n"); return; } int main(){ while(scanf("%d%d", &r, &c), c&&r){ for(int i=0; i<r; i++){ scanf("%s", G[i]); for(int j=0; j<c; j++){ if(G[i][j]=='*') s_x=i, s_y=j; } } bfs(); } return 0; }