-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBfs01.cpp
More file actions
76 lines (65 loc) · 1.59 KB
/
Copy pathBfs01.cpp
File metadata and controls
76 lines (65 loc) · 1.59 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
65
66
67
68
69
70
71
72
73
74
75
76
#include <bits/stdc++.h>
#define _ \
ios_base::sync_with_stdio(0); \
cin.tie(0);
#define endl '\n'
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3fll;
void solve() {
int n, m;
cin >> n >> m;
vector<string> arr(n);
for (auto &i : arr)
cin >> i;
int dx[4] = {0, -1, 1, 0};
int dy[4] = {1, 0, 0, -1};
auto isValid = [&](int x, int y) -> bool {
return (0 <= x && x < n && 0 <= y && y < m);
};
vector<vector<int>> dist(n, vector<int>(m, INF));
dist[0][0] = 0;
vector<vector<bool>> vis(n, vector<bool>(m, false));
deque<pair<int, int>> dq;
dq.push_front({0, 0});
while (!dq.empty()) {
auto curr = dq.front();
dq.pop_front();
int u = curr.first;
int v = curr.second;
if (vis[u][v]) continue;
vis[u][v] = true;
for (int i = 0; i < 4; i++) {
int cx = u + dx[i];
int cy = v + dy[i];
if (isValid(cx, cy)) {
bool ok = true;
if (arr[u][v] != arr[cx][cy])
ok = false;
if (dist[u][v] + !ok < dist[cx][cy]) {
dist[cx][cy] = dist[u][v] + !ok;
if (!ok) {
dq.push_back({cx, cy});
} else {
dq.push_front({cx, cy});
}
}
}
}
}
cout << dist[n - 1][m - 1] << endl;
}
int main() {
_
int t;
if (cin >> t) {
while (t--) {
solve();
}
}
return 0;
}