Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <queue>
- #include <stdlib.h>
- #include <string.h>
- #define MAX 910
- using namespace std;
- int n, m, x0, y0;
- int result;
- typedef struct {
- int x;
- int y;
- } POINT;
- queue<POINT> q; // queue for cell
- bool maze[MAX][MAX];
- bool visited[MAX][MAX]; // visited[i][j] = 1 -> cell (i, j) visited
- int level[MAX][MAX]; // level[i][j] shortest distance from state (0, 0) to (i, j)
- void output () {
- printf("%d\n", result);
- }
- void dfs () {
- while (!q.empty()) {
- POINT cur = q.front();
- q.pop();
- int xnextf = cur.x + 1;
- int ynextf = cur.y + 1;
- int xnextb = cur.x - 1;
- int ynextb = cur.y - 1;
- if (xnextf > n || xnextb < 1 || ynextf > m || ynextb < 1) {
- result = level[cur.x][cur.y] + 1;
- return;
- }
- POINT tmp;
- if (!maze[xnextf][cur.y] && !visited[xnextf][cur.y]) {
- tmp.x = xnextf;
- tmp.y = cur.y;
- q.push(tmp);
- level[xnextf][cur.y] = level[cur.x][cur.y] + 1;
- visited[tmp.x][tmp.y] = 1;
- }
- if (!maze[xnextb][cur.y] && !visited[xnextb][cur.y]) {
- tmp.x = xnextb;
- tmp.y = cur.y;
- q.push(tmp);
- level[xnextb][cur.y] = level[cur.x][cur.y] + 1;
- visited[tmp.x][tmp.y] = 1;
- }
- if (!maze[cur.x][ynextf] && !visited[cur.x][ynextf]) {
- tmp.x = cur.x;
- tmp.y = ynextf;
- q.push(tmp);
- level[cur.x][ynextf] = level[cur.x][cur.y] + 1;
- visited[tmp.x][tmp.y] = 1;
- }
- if (!maze[cur.x][ynextb] && !visited[cur.x][ynextb]) {
- tmp.x = cur.x;
- tmp.y = ynextb;
- q.push(tmp);
- level[cur.x][ynextb] = level[cur.x][cur.y] + 1;
- visited[tmp.x][tmp.y] = 1;
- }
- }
- result = -1;
- }
- void solve () {
- POINT tmp = {x0, y0};
- q.push(tmp);
- level[x0][y0] = 0;
- visited[x0][y0] = 1;
- dfs();
- }
- void input () {
- scanf("%d%d%d%d", &n, &m, &x0, &y0);
- for (int i = 1; i <= n; ++i) {
- for (int j = 1; j <= m; ++j)
- scanf("%d", &maze[i][j]);
- }
- memset(visited, 0, sizeof(visited));
- memset(level, 0, sizeof(level));
- }
- int main () {
- // freopen("inp", "r", stdin);
- // freopen("out", "w", stdout);
- input();
- solve();
- output();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement