题意 在一个矩阵里,救唐僧,要求在矩阵中收集够钥匙,才能救。另外,一些cell中有蛇,通过这样的房间要杀掉蛇并多花一分钟,普通走一步花1分钟,最后问你最少花费多少时间。
思路 做这题,本来想要练练A*的,结果h函数设计的还是不够好,WA了,没办法,还是让h函数为0过了...之后还得想再设计一些h函数试试~
这题中蛇不超过5只,用状态压缩一发就行了~其它的就是有些琐碎实现的时候要多注意一下就好了~
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
#include <cmath>
using namespace std;
#define maxn 110
typedef pair<int,int> PII;
#define fi first
#define se second
#define MP make_pair
#define PB push_back
const int inf = 0x3f3f3f3f;
PII drct[4];
char mapp[maxn][maxn];
int mark[maxn][maxn][10][32];
vector<PII> vec[12];
int marks[maxn][maxn];
PII start;
int n,m,S;
struct Node{
int x,y,k,s,dp,pri;
Node(int x=0,int y=0,int k=0,int s=0,int dp=0,int pri=0):x(x),y(y),k(k),s(s),dp(dp),pri(pri){
}
/*int setPri()
{
//int ans = 0;
int value =inf;
pri = 0;
int x1 = x,y1 = y;
for(int i=k;i<=m;i++)
{
value = inf;
int x2,y2;
for(int j=0;j<vec[i].size();j++)
{
int tmp = abs(vec[i][j].fi-x1)+abs(vec[i][j].se-y1);
if(tmp < value)
{
value = tmp;
x2 = vec[i][j].fi;
y2 = vec[i][j].se;
}
}
pri += value;
x1 = x2;
y1 = y2;
}
/*for(int i=0;i<vec[k].size();i++)
{
int tmp = abs(vec[k][i].fi-x)+abs(vec[k][i].se-y);
if(tmp < value)
{
value = tmp;
}
}
return pri;
}*/
};
bool operator<(Node x,Node y)
{
//return x.k < y.k || x.k==y.k && x.pri+x.dp > y.pri+y.dp;
//return x.pri+x.dp > y.pri+y.dp;
return x.dp > y.dp;
}
priority_queue<Node> q;
void init()
{
memset(mark,0,sizeof(mark));
memset(marks,-1,sizeof(marks));
for(int i=0;i<=m;i++)
vec[i].clear();
while(q.size()!=0)
q.pop();
S = 0;
drct[0].fi = 0;
drct[0].se = 1;
drct[1].fi = 0;
drct[1].se = -1;
drct[2].fi = 1;
drct[2].se = 0;
drct[3].fi = -1;
drct[3].se = 0;
}
void input()
{
int i,j;
for(i=0;i<n;i++)
{
getchar();
for(j=0;j<n;j++)
{
mapp[i][j] = getchar();
if(mapp[i][j] == 'S')
{
marks[i][j] = S++;
}
else if(mapp[i][j] == 'T')
{
vec[m].PB(MP(i,j));
}
else if(mapp[i][j] == 'K')
{
start = MP(i,j);
}
else if(mapp[i][j]>='1' && mapp[i][j] <= '9')
{
vec[mapp[i][j] - '1'].PB(MP(i,j));
}
}
}
}
int main()
{
int i,j;
while(scanf("%d%d",&n,&m)==2 && n)
{
init();
input();
Node tmp = Node(start.fi,start.se,0,(1<<S)-1);
Node tmp2;
//tmp.setPri();
q.push(tmp);
int ans = 0;
while(q.size()!=0)
{
tmp = q.top();
q.pop();
for(i=0;i<4;i++)
{
if(tmp.x + drct[i].fi < 0 || tmp.x + drct[i].fi >= n
|| tmp.y+ drct[i].se < 0 || tmp.y + drct[i].se >= n)
continue;
int x = tmp.x + drct[i].fi;
int y = tmp.y+ drct[i].se;
if(mapp[x][y] == '#')
continue;
int k,s,dp;
if((int)(mapp[x][y]-'1') == tmp.k)
k = tmp.k + 1;
else if(mapp[x][y] == 'T' && tmp.k == m)
{
ans = tmp.dp + 1;
break;
}
else
k = tmp.k;
if(mapp[x][y] == 'S' && ((tmp.s>>marks[x][y])&1)==1)
{
dp = tmp.dp + 2;
s = tmp.s & ~(1<<marks[x][y]);
}
else
{
dp = tmp.dp + 1;
s = tmp.s;
}
if(mark[x][y][k][s] == 1)
continue;
tmp2 = Node(x,y,k,s,dp);
mark[x][y][k][s] = 1;
//tmp2.setPri();
q.push(tmp2);
}
if(ans > 0)
break;
}
if(ans == 0)
cout<<"impossible\n";
else
cout<<ans<<endl;
}
return 0;
}