Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <fstream>
- #include <queue>
- using namespace std;
- const int N = 1111;
- const int INF = 1e9;
- const int dx[] = {-1, -2, -2, -1, 1, 2, 2, 1}, dy[] = {-2, -1, 1, 2, 2, 1, -1, -2};
- int a[N][N], n, m, d[N][N], cur, xs, ys, xf, yf;
- queue<int> qx[3], qy[3];
- void bfs() {
- qx[cur].push(xs);
- qy[cur].push(ys);
- d[xs][ys] = 0;
- while (!qx[0].empty() || !qx[1].empty() || !qx[2].empty()) {
- int x = qx[cur].front(), y = qy[cur].front();
- qx[cur].pop(); qy[cur].pop();
- for (int t = 0; t < 8; ++t) {
- int tx = x + dx[t], ty = y + dy[t];
- if (tx < 1 || tx > n || ty < 1 || ty > m || a[tx][ty] == -1) continue;
- int w = 1 + a[tx][ty];
- if (d[tx][ty] > d[x][y] + w) {
- d[tx][ty] = d[x][y] + w;
- qx[(cur + w) % 3].push(tx);
- qy[(cur + w) % 3].push(ty);
- }
- }
- if (qx[cur].empty()) cur = (cur + 1) % 3;
- if (qx[cur].empty()) cur = (cur + 1) % 3;
- }
- }
- int main(){
- ifstream fin("in.txt");
- ofstream fout("out.txt");
- fin >> n >> m;
- for (int i = 1; i <= n; ++i)
- for (int j = 1; j <= m; ++j) {
- fin >> a[i][j];
- d[i][j] = INF;
- }
- fin >> xs >> ys >> xf >> yf;
- bfs();
- if (d[n][m] < INF) fout << d[xf][yf];
- else fout << "No";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment