Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

http://codeforces.

com/problemset/problem/3/A
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_p
roblem&problem=1594
http://en.wikipedia.org/wiki/Depth-first_search
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <map>
#include <utility>
#include <sstream>
#include <string>
#include <cstring>
#include <cctype>
#include <cmath>
#include <queue>
#include <stack>
#include <set>
//int dx[8] = {1,0,-1,0,1,1,-1,-1};
//int dy[8] = {0,1,0,-1,1,-1,1,-1};
#define N 1005
using namespace std;
int A[N][N];//1 si hay bomba 0 si no
//BFS
int vis[N][N];
int d[N][N];
struct nodo {
int x, y;
nodo(int x, int y) : x(x), y(y) {}
nodo() {}
};
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int main() {
int n,m;
while( scanf("%d%d", &n, &m) == 2, n != 0) {
memset(A, 0, sizeof A);
memset(vis, 0, sizeof vis);
memset(d, -1, sizeof d);
int filasConBombas;
scanf("%d", &filasConBombas);
for(int i = 0;i < filasConBombas; i++) {
int fila, nBombas, col;
scanf("%d%d", &fila, &nBombas);
for (int j = 0; j < nBombas; j++) {
scanf("%d", &col);
A[fila][col] = 1;
}
}
int xi,yi, xf, yf;

scanf("%d%d%d%d", &xi, &yi, &xf, &yf);

queue<nodo> Q;
Q.push(nodo(xi,yi));
d[xi][yi] = 0;
while(!Q.empty()) {
nodo q = Q.front();
Q.pop();
for (int i = 0; i < 4; i++) {
int nx = q.x + dx[i];
int ny = q.y + dy[i];
if (0<=nx && nx < n && 0<=ny && ny<m && !vis[nx][ny] && !A[nx][ny] ) {
Q.push(nodo(nx, ny));
vis[nx][ny] = 1;
d[nx][ny] = d[q.x][q.y] + 1;
}
}
}
cout << d[xf][yf] << endl;
}
}

You might also like