-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.sh
90 lines (82 loc) · 1.36 KB
/
bfs.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
struct N
{
int x, y, z;
int t;
};
bool mark[50][50][50];
int maze[50][50][50];
queue<N> Q;
int go[][3] = {1, 0, 0,
-1, 0, 0,
0, 1, 0,
0, -1, 0,
0, 0, 1,
0, 0, -1
};
int BFS(int a, int b, int c)
{
while (!Q.empty())
{
N now = Q.front();
Q.pop();
for (int i = 0; i < 6; ++i)
{
int nx = now.x + go[i][0];
int ny = now.y + go[i][1];
int nz = now.z + go[i][2];
if (nx < 0 || nx >= a || ny < 0 || ny >= b || nz < 0 || nz >= c)
continue;
if (maze[nx][ny][nz] == 1)
continue;
if (maze[nx][ny][nz] == true)
continue;
N temp;
temp.x = nx;
temp.y = ny;
temp.z = nz;
temp.t = now.t + 1;
Q.push(temp);
mark[nx][ny][nz] == true;
if (nx == a - 1 && ny == b - 1 && nz == c - 1)return temp.t;
}
}
return -1;
}
int main()
{
int T;
cin >> T;
while (T--)
{
int a, b, c, t;
cin >> a >> b >> c >> t;
for (int i = 0; i < a; ++i)
{
for (int j = 0; j < b; ++j)
{
for (int k = 0; k < c; ++k)
{
cin >> maze[i][j][k];
mark[i][j][k] = false;
}
}
}
while (!Q.empty())
Q.pop();
mark[0][0][0] = true;
N temp;
temp.t = temp.x = temp.y = temp.z = 0;
Q.push(temp);
int rec=BFS(a,b,c);
if (rec<= t)
cout<<rec<<endl;
else
cout<<"-1"<<endl;
}
return 0;
}