-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortest_Distance.cpp
More file actions
64 lines (51 loc) · 1.21 KB
/
Shortest_Distance.cpp
File metadata and controls
64 lines (51 loc) · 1.21 KB
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
#include <bits/stdc++.h>
using namespace std;
bool vis[100][100];
int dis[100][100];
vector<pair<int, int>> d = {{2, 1}, {2, -1}, {-2, 1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};
bool valid(int i, int j, int n, int m)
{
return i >= 0 && i < n && j >= 0 && j < m;
}
void bfs(int si, int sj, int n, int m)
{
queue<pair<int, int>> q;
q.push({si, sj});
vis[si][sj] = true;
dis[si][sj] = 0;
while (!q.empty())
{
pair<int, int> par = q.front();
int a = par.first, b = par.second;
q.pop();
for (int i = 0; i < 8; i++)
{
int ci = a + d[i].first;
int cj = b + d[i].second;
if (valid(ci, cj, n, m) && !vis[ci][cj])
{
q.push({ci, cj});
vis[ci][cj] = true;
dis[ci][cj] = dis[a][b] + 1;
}
}
}
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n, m;
cin >> n >> m;
int si, sj, di, dj;
cin >> si >> sj;
cin >> di >> dj;
memset(vis, false, sizeof(vis));
memset(dis, -1, sizeof(dis));
bfs(si, sj, n, m);
cout << dis[di][dj] << endl;
}
return 0;
}