Cod sursa(job #865844)

Utilizator ELHoriaHoria Cretescu ELHoria Data 27 ianuarie 2013 10:00:35
Problema Car Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.74 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#define pii pair<int,int>
#define x first
#define y second
#define mp make_pair

using namespace std;
  
ifstream cin("car.in");
ofstream cout("car.out");
				 //N NE E SE S SV V NV
const int dx[] = {-1,-1,0,1,1,1,0,-1};
const int dy[] = {0,1,1,1,0,-1,-1,-1};
const int NMAX = 512, inf = int(1e9);
int N, M;
bool isFree[NMAX][NMAX];
int cost[NMAX][NMAX];
pii S, D;


void readData() {
	cin>>N>>M;
	cin>>S.x>>S.y>>D.x>>D.y;
	for(int i = 1;i <= N;i++) {
		for(int j = 1;j <= M;j++) {
			cin>>isFree[i][j];
		}
	}
}

int bf() {
	for(int i = 1;i <= N;i++) { 
		for(int j = 1;j <= M;j++) {
			cost[i][j] = inf;	
			isFree[i][j] ^= 1;
		}
	}
	cost[S.x][S.y] = 0;
	queue< pair<pii,char> > q;
	for(int k = 0;k < 8;k++) {
		q.push(mp(S,k));
	}
	pii v, w;
	int dir;
	while(!q.empty()) {
		v = q.front().x;
		dir = (int)q.front().y;
		q.pop();
		w = mp(v.x + dx[dir],v.y + dy[dir]);
		if(isFree[w.x][w.y] && cost[w.x][w.y] > cost[v.x][v.y]) {
			cost[w.x][w.y] = cost[v.x][v.y];
			q.push(mp(w,(char)dir));
		}
		for(int k = 1;k <= 4;k++) {
			int Left = dir - k;
			int Right = dir + k;
			if(Left < 0) Left += 8;
			if(Right > 7) Right -= 8;
			w = mp(v.x + dx[Left],v.y + dy[Left]);
			if(isFree[w.x][w.y] && cost[w.x][w.y] > cost[v.x][v.y] + k) { 
				cost[w.x][w.y] = cost[v.x][v.y] + k;
				q.push(mp(w,(char)Left));
			}
			w = mp(v.x + dx[Right],v.y + dy[Right]);
			if(isFree[w.x][w.y] && cost[w.x][w.y] > cost[v.x][v.y] + k) { 
				cost[w.x][w.y] = cost[v.x][v.y] + k;
				q.push(mp(w,(char)Right));
			}
		}
	}
	return cost[D.x][D.y] == inf ? -1 : cost[D.x][D.y];
}

int main()
{
	readData();
	cout<<bf();
    return 0;
}