-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSah2.cpp
More file actions
109 lines (95 loc) · 2.68 KB
/
Copy pathSah2.cpp
File metadata and controls
109 lines (95 loc) · 2.68 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <fstream>
#include <queue>
using namespace std;
ifstream cin("sah2.in");
ofstream cout("sah2.out");
const int cal_i[] = {-2, -2, -1, 1, 2, 2, 1, -1};
const int cal_j[] = {-1, 1, 2, 2, 1, -1, -2, -2};
const int di[] = {-1, -1, 1, 1};
const int dj[] = {-1, 1, 1, -1};
const int NMAX = 505;
const int INF = 1000;
int n, r0, c0, r1, c1, dp[NMAX][NMAX], miscariCal[NMAX][NMAX];
char t[NMAX][NMAX];
struct Punct {
int row, col, moves;
bool operator< (Punct A) const {
return moves < A.moves;
}
};
void Citire() {
cin >> n >> r0 >> c0 >> r1 >> c1;
for (int i = 1; i <= n; i++)
cin >> (t[i] + 1);
}
void Init() {
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = INF, miscariCal[i][j] = -1;
}
inline bool Ok(int i, int j) {
if (i < 1 || j < 1 || i > n || j > n)
return false;
if (t[i][j] == '1')
return false;
return true;
}
void Lee(int i, int j) {
int noul_i, noul_j, miscari;
queue<Punct> q;
Punct w;
w.row = i;
w.col = j;
w.moves = 2;
q.push(w);
dp[i][j] = 0;
miscariCal[i][j] = 2;
while (!q.empty()) {
i = q.front().row;
j = q.front().col;
miscari = q.front().moves;
q.pop();
if (i == r1 && j == c1) {
cout << dp[r1][c1] << '\n';
return;
}
if (miscari > 0)
for (int k = 0; k < 8; k++) {
noul_i = i + cal_i[k];
noul_j = j + cal_j[k];
if (Ok(noul_i, noul_j) && (dp[noul_i][noul_j] > 1 + dp[i][j] ||
miscariCal[noul_i][noul_j] < miscari - 1)) {
dp[noul_i][noul_j] = 1 + dp[i][j];
miscariCal[noul_i][noul_j] = miscari - 1;
w.row = noul_i;
w.col = noul_j;
w.moves = miscari - 1;
q.push(w);
}
}
for (int k = 0; k < 4; k++) {
for (int pas = 1; ; pas++) {
noul_i = i + di[k] * pas;
noul_j = j + dj[k] * pas;
if (!Ok(noul_i, noul_j)) break;
if (dp[noul_i][noul_j] > 1 + dp[i][j] ||
miscariCal[noul_i][noul_j] < miscari) {
dp[noul_i][noul_j] = 1 + dp[i][j];
miscariCal[noul_i][noul_j] = miscari;
w.row = noul_i;
w.col = noul_j;
w.moves = miscari;
q.push(w);
}
}
}
}
}
signed main() {
Citire();
Init();
Lee(r0, c0);
cin.close();
cout.close();
return 0;
}