题目链接:http://bailian.openjudge.cn/practice/4130?lang=en_US
总时间限制: 1000ms 内存限制: 65536kB

描述

《Journey to the West》(also 《Monkey》) is one of the Four Great Classical Novels of Chinese literature. It was written by Wu Cheng'en during the Ming Dynasty. In this novel, Monkey King Sun Wukong, pig Zhu Bajie and Sha Wujing, escorted Tang Monk to India to get sacred Buddhism texts.

During the journey, Tang Monk was often captured by demons. Most of demons wanted to eat Tang Monk to achieve immortality, but some female demons just wanted to marry him because he was handsome. So, fighting demons and saving Monk Tang is the major job for Sun Wukong to do.

Once, Tang Monk was captured by the demon White Bones. White Bones lived in a palace and she cuffed Tang Monk in a room. Sun Wukong managed to get into the palace. But to rescue Tang Monk, Sun Wukong might need to get some keys and kill some snakes in his way.

The palace can be described as a matrix of characters. Each character stands for a room. In the matrix, 'K' represents the original position of Sun Wukong, 'T' represents the location of Tang Monk and 'S' stands for a room with a snake in it. Please note that there are only one 'K' and one 'T', and at most five snakes in the palace. And, '.' means a clear room as well '#' means a deadly room which Sun Wukong couldn't get in.

There may be some keys of different kinds scattered in the rooms, but there is at most one key in one room. There are at most 9 kinds of keys. A room with a key in it is represented by a digit(from '1' to '9'). For example, '1' means a room with a first kind key, '2' means a room with a second kind key, '3' means a room with a third kind key... etc. To save Tang Monk, Sun Wukong must get ALL kinds of keys(in other words, at least one key for each kind).

For each step, Sun Wukong could move to the adjacent rooms(except deadly rooms) in 4 directions(north,west,south and east), and each step took him one minute. If he entered a room in which a living snake stayed, he must kill the snake. Killing a snake also took one minute. If Sun Wukong entered a room where there is a key of kind N, Sun would get that key if and only if he had already got keys of kind 1,kind 2 ... and kind N-1. In other words, Sun Wukong must get a key of kind N before he could get a key of kind N+1 (N>=1). If Sun Wukong got all keys he needed and entered the room in which Tang Monk was cuffed, the rescue mission is completed. If Sun Wukong didn't get enough keys, he still could pass through Tang Monk's room. Since Sun Wukong was a impatient monkey, he wanted to save Tang Monk as quickly as possible. Please figure out the minimum time Sun Wukong needed to rescue Tang Monk.

输入

There are several test cases.

For each case, the first line includes two integers N and M(0 < N <= 100, 0 < M <= 9), meaning that the palace is a N * N matrix and Sun Wukong needed M kinds of keys(kind 1, kind 2, ... kind M). 

Then the N*N matrix follows.

The input ends with N = 0 and M = 0.

输出

For each test case, print the minimum time (in minute) Sun Wokong needed to save Tang Monk. If it's impossible for Sun Wokong to complete the mission, print "impossible".

样例输入

3 1
K.S
##1
1#T
3 1
K#T
.S#
1#.
3 2
K#T
.S.
21.
0 0

样例输出

5
impossible
8

解题思路

题意:给一个地图,孙悟空(K)救唐僧(T),地图中'S'表示蛇,第一次到这要杀死的蛇(蛇最多5条),多花费一分钟,'1'~'m'表示m个钥匙(m<=9),孙悟空要依次拿到这m个钥匙,然后才能去救唐僧,集齐m个钥匙之前可以经过唐僧,问最少多少步救到唐僧。
思路:BFS,每个节点维护5个值:
x, y:当前坐标,k:已经集齐了k个钥匙,t:已经走了多少步,s:s的二进制位为1代表该蛇已被杀死。
可以用一个三维数组保存spt[x][y][k]此时的最小步数,也可以用优先队列。

Accepted Code:

//三维计步
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 105;
const int inf = 0x3f3f3f3f;
map <pair <int, int>, int> snake;
char mp[MAXN][MAXN];
int n, spt[MAXN][MAXN][MAXN >> 3];
int dir[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
struct edge {
    int x, y, t, k, s;
    edge(int x_, int y_, int t_, int k_, int s_) : x(x_), y(y_), t(t_), k(k_), s(s_) {}
};
void BFS(int x, int y) {
    queue <edge> Q;
    spt[x][y][0] = 0;
    Q.push(edge(x, y, 0, 0, 0));
    while (!Q.empty()) {
        edge p = Q.front();
        Q.pop();
        for (int i = 0; i < 4; i++) {
            int tx = p.x + dir[i][0];
            int ty = p.y + dir[i][1];
            if (tx >= 0 && tx < n && ty >= 0 && ty < n && mp[tx][ty] != '#') {
                int t = p.t + 1, k = p.k, s = p.s;
                if (mp[tx][ty] == 'S' && !(s >> snake[make_pair(tx, ty)] & 1)) {
                    t++;
                    s |= 1 << snake[make_pair(tx, ty)];
                }
                if (mp[tx][ty] == k + '1')
                    k++;
                if (t < spt[tx][ty][k]) {
                    spt[tx][ty][k] = t;
                    Q.push(edge(tx, ty, t, k, s));
                }
            }
        }
    }
}
int main() {
    int m, sx, sy, ex, ey, cnt;
    while (~scanf("%d%d", &n, &m), n + m) {
        cnt = 0;
        memset(spt, 0x3f, sizeof(spt));
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                scanf(" %c", &mp[i][j]);
                if (mp[i][j] == 'K')
                    sx = i, sy = j;
                else if (mp[i][j] == 'T')
                    ex = i, ey = j;
                else if (mp[i][j] == 'S')
                    snake[make_pair(i, j)] = cnt++;
            }
        }
        BFS(sx, sy);
        if (spt[ex][ey][m] < inf)
            printf("%d\n", spt[ex][ey][m]);
        else printf("impossible\n");
    }
    return 0;
}
//优先队列
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 105;
const int inf = 0x3f3f3f3f;
map <pair <int, int>, int> snake;
char mp[MAXN][MAXN];
bool vis[MAXN][MAXN][MAXN >> 3];
int dir[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
struct edge {
    int x, y, t, k, s;
    edge(int x_, int y_, int t_, int k_, int s_) : x(x_), y(y_), t(t_), k(k_), s(s_) {}
    bool operator < (const edge &s) const {
        return s.t < t;
    }
};
void BFS(int x, int y, int n, int m) {
    vis[x][y][0] = true;
    priority_queue <edge> Q;
    Q.push(edge(x, y, 0, 0, 0));
    while (!Q.empty()) {
        edge p = Q.top();
        Q.pop();
        if (!(mp[p.x][p.y] != 'T' || p.k != m)) {
            printf("%d\n", p.t);
            return ;
        }
        for (int i = 0; i < 4; i++) {
            int tx = p.x + dir[i][0];
            int ty = p.y + dir[i][1];
            int t = p.t + 1, k = p.k, s = p.s;
            if (mp[tx][ty] == k + '1')
                k++;
            if (tx >= 0 && tx < n && ty >= 0 && ty < n && mp[tx][ty] != '#' && !vis[tx][ty][k]) {
                if (mp[tx][ty] == 'S' && !(s >> snake[make_pair(tx, ty)] & 1)) {
                    t++;
                    s |= 1 << snake[make_pair(tx, ty)];
                }
                vis[tx][ty][k] = true;
                Q.push(edge(tx, ty, t, k, s));
            }
        }
    }
    printf("impossible\n");
}
int main() {
    int m, n, sx, sy, cnt;
    while (~scanf("%d%d", &n, &m), n + m) {
        cnt = 0;
        memset(vis, false, sizeof(vis));
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                scanf(" %c", &mp[i][j]);
                if (mp[i][j] == 'K')
                    sx = i, sy = j;
                else if (mp[i][j] == 'S')
                    snake[make_pair(i, j)] = cnt++;
            }
        }
        BFS(sx, sy, n, m);
    }
    return 0;
}