Cod sursa(job #1343159)

Utilizator aimrdlAndrei mrdl aimrdl Data 14 februarie 2015 22:43:15
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <unistd.h>

#define BLOCKED -1

using namespace std;

struct pos{
	short x;
	short y;
	
	void set(short a, short b);
};

void pos::set (short a, short b) {
	x = a;
	y = b;
}

int m, k;
pos S, E;

void print (short **M) {
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < m; j++) {
			cout << M[i][j] << " ";
		}
		cout << "\n";
	}
}

short ** read (ifstream &in) {
	in >> m >> k;
	
	short **M = new short *[m];
	for (int i = 0; i < m; i++) {
		M[i] = new short[m]();
	}
	
	for (int i = 0; i < k; i++) {
		int x, y;
		in >> x >> y;
		M[x - 1][y - 1] = BLOCKED;
	}
	
	in >> S.x >> S.y >> E.x >> E.y;
	
	--S.x; --S.y; --E.x; --E.y;
	
	M[S.x][S.y] = 1;
	
	return M;
}	

void lee (short **M) {
	M[S.x][S.y] = 1;
	
	vector <pos> Q;
	Q.push_back(S);
	
	int i = 0;
	
	while (Q.at(i).x != E.x || Q.at(i).y != E.y) {
		pos t = Q.at(i);
		pos aux;
		int mark = M[t.x][t.y] + 1;
		
		if (t.x != 0) {
			if (M[t.x - 1][t.y] == 0) {	
				M[t.x - 1][t.y] = mark;
				aux.set(t.x - 1, t.y);
				Q.push_back(aux);
			}
		}
		if (t.x != m - 1) {
			if (M[t.x + 1][t.y] == 0) {	
				M[t.x + 1][t.y] = mark;
				aux.set(t.x + 1, t.y);
				Q.push_back(aux);
			}
		}
		if (t.y != 0) {
			if (M[t.x][t.y - 1] == 0) {	
				M[t.x][t.y - 1] = mark;
				aux.set(t.x, t.y - 1);
				Q.push_back(aux);
			}
		}
		if (t.y != m - 1) {
			if (M[t.x][t.y + 1] == 0) {	
				M[t.x][t.y + 1] = mark;
				aux.set(t.x, t.y + 1);
				Q.push_back(aux);
			}
		}		
		
		Q.erase(Q.begin() + i);
		i = 0;
	}
}
	
	

int main (void) {
	ifstream in ("alee.in");
	ofstream out ("alee.out");
	
	short **M = read(in);
	
	lee(M);
	
	out << M[E.x][E.y];
	
	for (int i = 0; i < m; i++) {
		delete[] M[i];
	}
	delete[] M;
	
	in.close();
	out.close();
	
	return 0;
}