给出M×N(M,N<=10)矩阵,其中有两个物体,1和2是两个物体的起始位置,-1和-2是两个物体的目标位置,9是障碍位置不能通过
两个物体每一步必须同时向上下左右中同一个方向移动,每次都要移动到边界或遇到障碍物为止
求最小移动多少步之后两个物体都处于目标位置,如果8步(包含)之内无法都到达目标位置,输出-1
输入:
用例数T
M,N
矩阵信息
输出:最小步数
4
5 5
0 1 0 0 0
0 0 0 0 0
0 2 0 9 0
0 0 0 0 0
0 9 -1 0 -2
4 6
-1 -2 1 0 9 0
0 2 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
7 4
0 0 0 0
0 0 0 9
2 0 1 0
0 0 9 0
0 9 0 0
0 0 0 0
-1 0 -2 0
4 7
0 0 0 0 0 0 0
0 0 1 9 0 0 0
0 0 0 0 0 0 0
9 2 -1 9 0 0 -2
#1 3
#2 4
#3 -1
#4 5
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int T, M, N, answer, data[10][10], flag[10][10][10][10], d[4][2] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
void dfs(int x1, int y1, int x2, int y2, int steps);
void move(int x1, int y1, int x2, int y2, int steps, int direction) {
bool moved;
do {
moved = false;
int newX1 = x1 + d[direction][0];
int newY1 = y1 + d[direction][1];
int newX2 = x2 + d[direction][0];
int newY2 = y2 + d[direction][1];
if (newX1 >= 0 && newX1 < M && newY1 >= 0 && newY1 < N && data[newX1][newY1] != 9
&& (newX1 != x2 || newY1 != y2)) {
x1 = newX1;
y1 = newY1;
moved = true;
}
if (newX2 >= 0 && newX2 < M && newY2 >= 0 && newY2 < N && data[newX2][newY2] != 9
&& (newX2 != x1 || newY2 != y1)) {
x2 = newX2;
y2 = newY2;
moved = true;
}
} while (moved);
if (flag[x1][y1][x2][y2] > steps + 1) {
flag[x1][y1][x2][y2] = steps + 1;
dfs(x1, y1, x2, y2, steps + 1);
}
}
void dfs(int x1, int y1, int x2, int y2, int steps) {
if ((steps > 8) || (answer != -1 && answer <= steps)) {
return;
}
if (data[x1][y1] == -1 && data[x2][y2] == -2) {
if (answer == -1 || answer > steps) {
answer = steps;
}
return;
}
for (int direction = 0; direction < 4; direction++) {
move(x1, y1, x2, y2, steps, direction);
}
}
int main(int argc, char** argv) {
freopen("sample_input.txt", "r", stdin);
setbuf(stdout, NULL);
scanf("%d", &T);
for (int test_case = 1; test_case <= T; ++test_case) {
scanf("%d", &M);
scanf("%d", &N);
int startX1, startY1, startX2, startY2;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
scanf("%d", &data[i][j]);
if (data[i][j] == 1) {
startX1 = i;
startY1 = j;
} else if (data[i][j] == 2) {
startX2 = i;
startY2 = j;
}
}
}
for (int i1 = 0; i1 < M; i1++) {
for (int j1 = 0; j1 < N; j1++) {
for (int i2 = 0; i2 < M; i2++) {
for (int j2 = 0; j2 < N; j2++) {
flag[i1][j1][i2][j2] = 999999;
}
}
}
}
answer = -1;
flag[startX1][startY1][startX2][startY2] = 0;
dfs(startX1, startY1, startX2, startY2, 0);
printf("#%d %d\n", test_case, answer);
}
return 0;
}