5 7 3 ....... ....1.. ..2#.3. ....... .......
9
样例:先去2,再去1,再去3。
5 8 3
....#..1
........
##...###
........
.2..#..3
25
先去2,再去3,再去1。
3 6 1
..#..1
..#...
..####
-1
代码:
#include <bits/stdc++.h>
using namespace std;
int n, m, k;
int mp[25][25];
struct qnode {
int x, y;
};
int tx[] = {0, -1, 0, 1};
int ty[] = {1, 0, -1, 0};
queue<qnode> que;
int dis[25][25], cost[25][25], vis[25][25];
void bfs(int sx, int sy)
{
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dis[i][j] = 1e9;
}
}
memset(vis, 0, sizeof(vis));
que.push({sx, sy});
vis[sx][sy] = 1;
dis[sx][sy] = 0;
while (que.size()) {
qnode tmp = que.front();
que.pop();
int x = tmp.x;
int y = tmp.y;
if (mp[x][y] >= 0 && mp[x][y] <= 9) {
cost[mp[sx][sy]][mp[x][y]] = cost[mp[x][y]][mp[sx][sy]] = dis[x][y];
}
for (int i = 0; i < 4; i++) {
int nx = x + tx[i];
int ny = y + ty[i];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && mp[nx][ny] != -2 && vis[nx][ny] == 0) {
dis[nx][ny] = dis[x][y] + 1;
vis[nx][ny] = 1;
que.push({nx, ny});
}
}
}
}
int used[20], ans = 1e9;
void dfs(int u, int val, int cnt)
{
used[u] = 1;
if (cnt == k) {
ans = min(ans, val);
}
for (int i = 1; i <= k; i++) {
if (used[i] == 0) {
dfs(i, val + cost[u][i], cnt + 1);
}
}
used[u] = 0;
}
int main()
{
cin >> n >> m >> k;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
char ch;
cin >> ch;
if (i == 1 && j == 1)
mp[i][j] = 0;
else {
if (ch == '.') {
mp[i][j] = -1;
} else if (ch == '#') {
mp[i][j] = -2;
} else {
mp[i][j] = ch - '0';
}
}
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (mp[i][j] >= 0 && mp[i][j] <= 9) {
bfs(i, j);
}
}
}
dfs(0, 0, 0);
if(ans==0) cout<<-1;
else cout << ans;
return 0;
}