Advertisement
Mattia-Iojica

Algoritmul lui Lee

Sep 22nd, 2019
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. ifstream fin("alee.in");
  8. ofstream fout("alee.out");
  9.  
  10. int di[4] = {0,  0, 1, -1};
  11. int dj[4] = {1, -1, 0,  1};
  12.  
  13. int N, M, Map[180][180];
  14. int startx, starty, stopx, stopy;
  15.  
  16. queue < pair < int, int > > coada;
  17.  
  18. void Citire()
  19. {
  20.     fin >> N >> M;
  21.     for(int i = 1; i <= M; i++)
  22.     {
  23.         int x, y;
  24.         fin >> x >> y;
  25.         Map[x][y] = -1; //Map[x][y] e obstacol
  26.     }
  27.     fin >> startx >> starty;
  28.     fin >> stopx >> stopy;
  29. }
  30.  
  31. bool OK(int i, int j)
  32. {
  33.     if(i < 1 || j < 1 || i > N || j > N) // Daca depaseste granitele
  34.         return false;
  35.     if(Map[i][j] == -1) // Daca intalneste un obstacol
  36.         return false;
  37.     return true;
  38. }
  39.  
  40. void Lee()
  41. {
  42.     int i, j, i_urmator, j_urmator;
  43.     Map[startx][starty] = 1;
  44.     coada.push(make_pair(startx, starty)); //Inserare pozitie de pornire in coada
  45.     while(!coada.empty()) // Verifica daca coada este libera
  46.     {
  47.         i = coada.front().first; // Extrage coordonata x a primului punct din coada
  48.         j = coada.front().second; // Extrage coordonata y a primului punct din coada
  49.         coada.pop();
  50.         for(int dir = 0; dir < 4; dir++)
  51.         {
  52.             i_urmator = i + di[dir];
  53.             j_urmator = j + dj[dir];
  54.             if(OK(i_urmator, j_urmator) && Map[i_urmator][j_urmator] < 1)
  55.             {
  56.                 Map[i_urmator][j_urmator] = Map[i][j] + 1;
  57.                 coada.push(make_pair(i_urmator, j_urmator));
  58.             }
  59.         }
  60.     }
  61. }
  62.  
  63. int main()
  64. {
  65.     Citire();
  66.     Lee();
  67.     fout << Map[stopx][stopy];
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement