4 5 17 @A.B. a*.*. *..*^ c..b* 4 5 16 @A.B. a*.*. *..*^ c..b*
16 -1
#include <iostream>
#include <queue>
#include <cstring>
using namespace std ;
struct Node{
int x , y ;
int time , key ;
};
bool visited[25][25][1050] ;
char map[25][25] ;
int n , m , lim;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}} ;
bool judge(Node t)
{
if(t.x<0||t.y<0 || t.x>=n||t.y>=m)
{
return false ;
}
return true ;
}
int bfs(int x , int y )
{
queue<Node> que ;
Node s ;
s.x = x , s.y = y ;
s.time = s.key = 0 ;
que.push(s) ;
memset(visited,false,sizeof(visited)) ;
while(!que.empty())
{
s = que.front() ;
que.pop() ;
if(map[s.x][s.y] == '^' && lim>s.time)
{
return s.time ;
}
if(lim<=s.time) break ;
for(int i = 0 ; i < 4 ; ++i)
{
Node next ;
next.x = s.x+dir[i][0] ;
next.y = s.y+dir[i][1] ;
next.time = s.time + 1 ;
next.key = s.key ;
if(!judge(next) || map[next.x][next.y] == '*')
continue ;
if(!visited[next.x][next.y][next.key])
{
if(map[next.x][next.y]>='A' && map[next.x][next.y]<='J')
{
if(next.key&(1<<(map[next.x][next.y]-'A')))
{
que.push(next) ;
visited[next.x][next.y][next.key] = true ;
}
}
else if(map[next.x][next.y]>='a' && map[next.x][next.y]<='j')
{
next.key = next.key|(1<<(map[next.x][next.y]-'a')) ;
que.push(next) ;
visited[next.x][next.y][next.key] = true ;
}
else
{
que.push(next) ;
visited[next.x][next.y][next.key] = true ;
}
}
}
}
return -1 ;
}
int main()
{
while(cin>>n>>m>>lim)
{
int x, y ;
for(int i = 0 ; i < n ; ++i)
{
cin>>map[i] ;
}
for(int i = 0 ; i < n ; ++i)
for(int j = 0 ; j < m ; ++j)
{
if(map[i][j] == '@')
{
x = i , y = j ;
break ;
}
}
int ans = bfs(x,y) ;
cout<<ans<<endl ;
}
return 0 ;
}hdu 1429 胜利大逃亡(续) 搜索+状态压缩,,不错的题。
原文:http://blog.csdn.net/lionel_d/article/details/44916637