题目链接
思路
基础题,多次bfs。
时间复杂度
$$ O(NMK) $$
代码
#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;
const int MAXN = 1010;
char s[MAXN][MAXN];
int step[MAXN][MAXN];
int n, m, k;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
pair<int, int> find(char c) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s[i][j] == c) {
return make_pair(i, j);
}
}
}
return make_pair(0, 0);
}
void init() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
step[i][j] = 0;
}
}
}
bool check(int x, int y) {
if (1 <= x && x <= n && 1 <= y && y <= m && s[x][y] != 'X') {
return true;
} else {
return false;
}
}
int bfs(pair<int, int> cur, char c) {
init();
queue<pair<int, int> > que;
que.push(cur);
while(!que.empty()) {
cur = que.front();
que.pop();
for (int i = 0; i < 4; i++) {
int xx = cur.first + dx[i];
int yy = cur.second + dy[i];
if (check(xx, yy) && step[xx][yy] == 0) {
step[xx][yy] = step[cur.first][cur.second] + 1;
que.push(make_pair(xx, yy));
if (s[xx][yy] == c) {
return step[xx][yy];
}
}
}
}
return 0;
}
int main() {
scanf("%d%d%d", &n, &m, &k);// don't forget &
for (int i = 1; i <= n; i++) {
scanf("%s", s[i] + 1);// no &
}
pair<int, int> cur = find('S');
int ans = 0;
for (int i = 1; i <= k; i++) {
ans += bfs(cur, '0' + i);
cur = find('0' + i);
}
printf("%d\n", ans);
return 0;
}