//有位运算 #include <iostream> #include <queue> using namespace std; //钥匙编号a,b...j 对应状态数中右数第0,1...9位 int hash[21][21][1100]; int pow[11] = {1,2,4,8,16,32,64,128,256,512}; int op[4][2] = {1,0,-1,0,0,1,0,-1}; //方向向量 int n,m,t; char map[21][21]; typedef struct { int x,y; int t; int state; //对应的10进制状态 }Node; Node start; int bfs() { queue<Node>Q; Q.push(start); while(!Q.empty()) { Node temp = Q.front(); Q.pop(); Node flag; for(int i=0; i<4; i++) { flag.x = temp.x + op[i][0]; flag.y = temp.y + op[i][1]; flag.t = temp.t + 1; flag.state = temp.state; if(flag.x < 0 || flag.x >= n || flag.y < 0 || flag.y >= m) { continue; } if(map[flag.x][flag.y] == '*') { continue; } char c = map[flag.x][flag.y]; if(c >= 'A' && c <= 'J') { if(!(flag.state >> (c - 'A')) & 1) //若身上没有对应的钥匙 { continue; } } if(c >= 'a' && c <= 'j' && !((flag.state >> (c-'a')) & 1)) { flag.state += pow[c-'a']; } if(c == '^') { if(flag.t < t) { return flag.t; } else { return -1; } } if(!hash[flag.x][flag.y][flag.state]) { Q.push(flag); hash[flag.x][flag.y][flag.state] = 1; } } } return -1; } int main() { int sign1,sign2; while(cin>>n>>m>>t) { sign1 = sign2 = 0; memset(hash,0,sizeof(hash)); for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { cin>>map[i][j]; if(map[i][j] == '@') { sign1 = 1; hash[i][j][0] = 1; start.x = i; start.y = j; start.t = 0; start.state = 0; } else if(map[i][j] == '^') { sign2 = 1; } } } //判断是否存在起点,终点 if(sign1 && sign2 ) { cout<<bfs()<<endl; } else { cout<<"-1"<<endl; } } return 0; }
// hdu 1429.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" //没有用位运算,直接开个数组标记 #include <iostream> #include <queue> using namespace std; int hash[21][21][1100]; int pow[11] = {1,2,4,8,16,32,64,128,256,512}; int op[4][2] = {1,0,-1,0,0,1,0,-1}; int n,m,t; char map[21][21]; typedef struct { int x,y; int t; int state; bool mark[10]; }Node; Node start; int bfs() { queue<Node>Q; Q.push(start); while(!Q.empty()) { Node temp = Q.front(); Q.pop(); Node flag; for(int i=0; i<4; i++) { flag = temp; flag.x += op[i][0]; flag.y += op[i][1]; flag.t += 1; if(flag.x < 0 || flag.x >= n || flag.y < 0 || flag.y >= m) { continue; } if(map[flag.x][flag.y] == '*') { continue; } char c = map[flag.x][flag.y]; if(c >= 'A' && c <= 'J') { if(!flag.mark[c-'A']) { continue; } } if(c >= 'a' && c <= 'j' && !flag.mark[c-'a']) { flag.state += pow[c-'a']; flag.mark[c-'a'] = 1; } if(c == '^') { if(flag.t < t) { return flag.t; } else { return -1; } } if(!hash[flag.x][flag.y][flag.state]) { Q.push(flag); hash[flag.x][flag.y][flag.state] = 1; } } } return -1; } int main() { int sign1,sign2; while(cin>>n>>m>>t) { sign1 = sign2 = 0; memset(hash,0,sizeof(hash)); for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { cin>>map[i][j]; if(map[i][j] == '@') { sign1 = 1; hash[i][j][0] = 1; start.x = i; start.y = j; start.t = 0; start.state = 0; memset(start.mark,0,sizeof(start.mark)); } else if(map[i][j] == '^') { sign2 = 1; } } } if(sign1 && sign2 ) { cout<<bfs()<<endl; } else { cout<<"-1"<<endl; } } return 0; }