此题纠结了很久,有个细节一定要注意,就是对于箱子要开三维数组做标记,因为从多个方向到达同一点他们的步数可能不一样,如果这个题目有WA的,记得检查一下这里,在此果断感谢Starry☆Sky 帮助我看代码。。
# include <iostream>
# include <queue>
using namespace std;
struct Node
{
int x, y;
int px, py;
int step;
}start;
const int Go[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int n, m;
int maze[10][10];
bool check(int x, int y)
{
return (x >= 0 && x < n && y >= 0 && y < m && maze[x][y] != 1);
}
int epx, epy;
int ebx, eby;
int check1;
bool visitedp[10][10];
void dfs(int x, int y)
{
if (x == epx && y == epy){
check1 = 1;
return ;
}
for (int i = 0; i < 4; i ++){
int xx = x + Go[i][0];
int yy = y + Go[i][1];
if (!check1&&check(xx, yy) && ((xx*10+yy) != (ebx*10+eby)) && !visitedp[xx][yy]){
visitedp[xx][yy] = 1;
dfs(xx, yy);
}
}
}
bool visitedb[10][10][4];
int ans;
queue <Node> Que;
void bfs()
{
while (!Que.empty())Que.pop();
memset(visitedb, 0, sizeof(visitedb));
Que.push(start);
while (!Que.empty()){
Node pre = Que.front();
Que.pop();
if (maze[pre.x][pre.y] == 3){
ans = pre.step;
return ;
}
for (int i = 0; i < 4; i ++){
int xx = pre.x + Go[i][0];
int yy = pre.y + Go[i][1];
if (i == 0){
epx = pre.x + Go[1][0];
epy = pre.y ;
}
if (i == 1){
epx = pre.x + Go[0][0];
epy = pre.y;
}
if (i == 2){
epx = pre.x;
epy = pre.y + Go[3][1];
}
if (i == 3){
epx = pre.x ;
epy = pre.y + Go[2][1];
}
check1 = 0;
ebx = pre.x, eby = pre.y;
memset(visitedp, 0, sizeof(visitedp));
visitedp[pre.px][pre.py] = 1;
int ppx = pre.px, ppy = pre.py;
dfs(ppx, ppy);
if (check(xx, yy) && check(epx, epy) && !visitedb[xx][yy][i]&& check1){
if (maze[pre.x][pre.y] == 3){
ans = pre.step;
return ;
}
Node next;
next.x = xx, next.y = yy;
next.px = epx, next.py = epy;
next.step = pre.step + 1;
visitedb[xx][yy][i] = 1;
Que.push(next);
}
}
}
}
int main()
{
int t;
scanf("%d", &t);
while (t --){
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i ++){
for (int j = 0; j < m; j ++){
scanf("%d", &maze[i][j]);
if (maze[i][j] == 2){
start.x = i, start.y = j;
start.step = 0;
}
if (maze[i][j] == 4){
start.px = i, start.py = j;
}
}
}
ans = -1;
bfs();
printf("%d/n", ans);
}
return 0;
}