这道题当时比赛的时候没有做起,应为要急着做毕业设计,也就没怎么认真思考。下来自己做的时候最开始的思路是深搜,后来发现深搜如果不剪枝的话肯定会超时的,于是乎就用了广搜
大体思路:
和普通的广搜一样一层一层的遍历,不过这里要用vis数组记录图上某个点是否被访问,其中的访问分为两种,一种是带着钥匙访问,一种是不带着钥匙访问,所以vis 数组应该开成三维数组。
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <cstdio>
#include <queue>
#include <cstring>
#define INF 0x3f3f3f3f
#define MAX_N 510
using namespace std;
struct node{
int x,y,step,k;
};
int dir[4][2] = {
{-1,0},
{1,0},
{0,1},
{0,-1}
};
int vis[MAX_N][MAX_N][2];
int n,m;
char g[MAX_N][MAX_N];
int bfs(int x,int y){
memset(vis,0,sizeof(vis));
queue<node> que;
node p;
p.x = x,p.y = y,p.k = 0,p.step = 0;
vis[x][y][0] = 1;
que.push(p);
while(!que.empty()){
node p = que.front();que.pop();
// printf("%d .. %d \n",p.x,p.y );
if (g[p.x][p.y] == 'E') return p.step;
for(int i = 0;i < 4;++i){
node q;
q.x = p.x + dir[i][0],q.y = p.y + dir[i][1];
if(0 <= q.x && q.x < n && 0 <= q.y && q.y < m && g[q.x][q.y] != '#'){
if(g[q.x][q.y] == 'K') q.k = 1;
else q.k = p.k;
// 如果已经访问了,就不必访问了
if(vis[q.x][q.y][q.k]) continue;
vis[q.x][q.y][q.k] = 1;
// 如果遇到E 但是没有钥匙,不能经过E这个点
if(g[q.x][q.y] == 'E' && !q.k) continue;
q.step = p.step + 1;
que.push(q);
}
}
}
return -1;
}
int main(){
// freopen("test.txt","r",stdin);
int T;
cin >> T;
while(T--){
int sx,sy;
cin >> n >> m;
for (int i = 0;i < n;++i){
scanf("%s",g[i]);
}
for (int i = 0;i < n;++i){
for (int j = 0;j < m;++j){
if(g[i][j] == 'P'){
sx = i,sy = j;
break;
}
}
}
int ans = -1;
ans = bfs(sx,sy);
if (ans != -1){
cout << ans << endl;
}
else{
cout << "No solution" << endl;
}
}
return 0;
}