Description
code4101听说这次选拔赛要他出3道题,吓得哭晕在厕所里一整天。第二天他早早的就去图书馆,废寝忘食(早餐午餐都没吃)的出题,晚上终于完成了。
现在他决定犒劳自己,去校内的两个食堂各吃一顿晚餐。
已知学校是个10*10的网格,code4101当前所在位置是A,他每次能从当前格移动到上下左右4格中的任意一格,学校内共有六个食堂,编号1,2,...,6。
code4101是路痴,不知道先去哪个食堂再去哪个食堂,使得总路程最短,所以只好请你来带路。
Input
输入数据的第一行为一个整数T,表示有T(0 < T < 20)组测试数据。
每个测试有10行,每行10个字符。字符’A’是起点,’1’~’6’代表6个食堂所在位置。除了’#’代表不能行走的障碍点,’.’等字符所在格子都是可以行走的通路。
每两个测试间会有一个空行。输入数据保证不会出现文中未提到的字符,且解一定存在。
Output
每个测试数据在一行输出一个数字,代表最小的总移动次数。
Sample Input
2
.......#12
..#....#.#
..##...A#.
.........#
...###....
..#.#..4..
.......#..
.5#.#.....
......3...
...6......
A......#..
..#......#
..##..1...
.........#
...###....
..#2#..4..
.......#..
.5#.#.....
......3...
...6......
Sample Output
7
12
思路: BFS暴力即可.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define min(a,b) (((a)<(b))?(a):(b))
const int inf = 0x3f3f3f3f;
using namespace std;
int mp[11][11];
int x[10], y[10];
int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0};
struct node {
int x, y, s;
node(int _x = 0, int _y = 0, int _s = 0):x(_x), y(_y), s(_s) {}
};
int dis(int sx,int sy,int ex,int ey) {
int vis[11][11] = {0};
queue<node> q;
q.push(node(sx, sy, 0));
vis[sx][sy] = 1;
while(!q.empty()) {
node now=q.front();
if(now.x == ex && now.y == ey) return now.s;
q.pop();
for(int k = 0; k <= 3; k++) {
int tx=now.x + dx[k];
int ty=now.y + dy[k];
if(tx <1 || tx > 10 || ty < 1 || ty > 10) continue;
if(mp[tx][ty] == 1 && vis[tx][ty] == 0) {
vis[tx][ty]=1;
q.push((node(tx, ty, now.s + 1)));
}
}
}
return inf;
}
int main() {
int n;
char ch;
cin >> n;
while(n--) {
for(int i = 1; i <= 10; i++)
for(int j = 1; j <= 10; j++) {
cin >> ch;
if(ch =='.') {
mp[i][j] = 1;
}
else if(ch =='#') {
mp[i][j] = 0;
}
else if( ch>'0' && ch <'7') {
mp[i][j] = 1;
x[ch - '0'] = i, y[ch - '0'] = j;
}
else if(ch == 'A') {
mp[i][j] = 1;
x[0] = i, y[0] = j;
}
}
int ans = inf;
for (int i = 1; i <= 6; i++)
for (int j = 1; j <= 6; j++) {
if (j == i) continue;
ans = min(ans, dis(x[0],y[0],x[i],y[i]) + dis(x[i],y[i],x[j],y[j]));
}
cout << ans << endl;
getchar();
}
return 0;
}