-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathABC_176_D.cpp
61 lines (53 loc) · 1.44 KB
/
ABC_176_D.cpp
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
#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i = 0; i < n; i++)
using ll = long long;
using graph = vector<vector<int>>;
const ll mod = 1000000007;
const int INF = 1001001001;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int h, w; cin >> h >> w;
vector<string> mp(h);
int sx, sy, gx, gy;
cin >> sx >> sy >> gx >> gy;
--sx; --sy; --gx; --gy;
for(int i = 0; i < h; i++) cin >> mp[i];
vector<vector<int>> cost(h, vector<int> (w, INF));
cost[sx][sy] = 0;
deque<pair<int, int>> que;
que.push_front({sx, sy});
while(!que.empty()){
auto p = que.front(); que.pop_front();
int x = p.first, y = p.second;
// using Move A
for(int i = 0; i < 4; i++){
int nx = x + dx[i], ny = y + dy[i];
if(nx < 0 || nx >= h || ny < 0 || ny >= w) continue;
if(mp[nx][ny] == '#') continue;
if(cost[nx][ny] > cost[x][y]){
cost[nx][ny] = cost[x][y];
que.push_front({nx, ny});
}
}
// using Move B
for(int i = -2; i <= 2; i++){
for(int j = -2; j <= 2; j++){
if(i == 0 && j == 0) continue;
int nx = x + i, ny = y + j;
if(nx < 0 || nx >= h || ny < 0 || ny >= w) continue;
if(mp[nx][ny] == '#') continue;
if(cost[nx][ny] > cost[x][y] + 1){
cost[nx][ny] = cost[x][y] + 1;
que.push_back({nx, ny});
}
}
}
}
int ans = cost[gx][gy] - cost[sx][sy];
if(ans == INF) cout << -1 << endl;
else cout << ans << endl;
}