Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <queue>
- #define dmax 1005
- using namespace std;
- ifstream fin ("traversare.in");
- ofstream fout ("traversare.out");
- int n, m, mat[dmax][dmax], mat_copie[dmax][dmax];
- void citire(){
- fin >> n >> m;
- for (int i = 1; i <= n; ++i)
- for (int j = 1; j <= m; ++j)
- fin >> mat[i][j];
- }
- struct Pos{
- int lin, col;
- };
- const int dL[] = {0, 0, 1, -1},
- dC[] = {1, -1, 0, 0};
- Pos s, f;
- queue <int> q;
- bool OK(int i, int j){
- if (i > n || j > m || i < 1 || j < 1)
- return false;
- if (mat[i][j] == 1)
- return false;
- return true;
- }
- void lee();
- void reset(){
- for (int i = 1; i <= n; ++i)
- for (int j = 1; j <= m; ++j)
- mat_copie[i][j] = mat[i][j];
- }
- int main(){
- int minim = 1000;
- for (int i = 1; i <= n; ++i){
- for (int j = 1; j <= m; ++j){
- if (mat[1][j] == 0 && mat[n][j]){
- s.lin = 1; s.col = j;
- lee();
- int nr = mat_copie[f.lin][f.col];
- reset();
- if (minim > nr)
- minim = nr;
- }
- }
- }
- fout << minim;
- return 0;
- }
- void lee(){
- mat[s.lin][s.col] = 1;
- q.push(s);
- while (!q.empty() && !mat_copie[f.lin][f.col]){
- Pos pos;
- q.pop();
- for (int k = 0; k < 4; ++k){
- Pos ngh;
- ngh.lin = pos.lin + dL[k];
- ngh.col = pos.col + dC[k];
- if (OK(ngh.lin, ngh.col) && !mat_copie[ngh.lin][ngh.col]){
- mat_copie[ngh.lin][ngh.col] = mat_copie[ngh.lin][ngh] + 1;
- q.push(ngh);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement