Advertisement
xerpi

BFS

Nov 20th, 2014
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <list>
  4. #include <queue>
  5. using namespace std;
  6.  
  7. typedef vector<char> FilaChar;
  8. typedef vector<FilaChar> MapaChar;
  9. typedef vector<bool> FilaBool;
  10. typedef vector<FilaBool> MapaBool;
  11.  
  12. struct PosDist {
  13.     int x, y, dist;
  14.     PosDist(int _x, int _y, int _dist) : x(_x), y(_y), dist(_dist) {}
  15. };
  16.  
  17. void print_queue(queue<PosDist> q)
  18. {
  19.     while (not q.empty()) {
  20.         PosDist p = q.front();
  21.         cout << "(" << p.x << ", " << p.y << ")" << endl;
  22.         q.pop();
  23.     }
  24. }
  25.  
  26. bool busca_tresor(MapaChar &map, int n, int m, int &dist, queue<PosDist> &q)
  27. {
  28.     while (not q.empty()) {
  29.         PosDist p = q.front();
  30.         q.pop();
  31.         if (map[p.x][p.y] == 't') {
  32.             dist = p.dist;
  33.             return true;
  34.         } else if (map[p.x][p.y] != 'X') {
  35.             map[p.x][p.y] = 'X';
  36.             if (p.x > 0) {
  37.                 q.push(PosDist(p.x - 1, p.y, p.dist + 1));
  38.             }
  39.             if (p.x < n-1) {
  40.                 q.push(PosDist(p.x + 1, p.y, p.dist + 1));
  41.             }
  42.             if (p.y > 0) {
  43.                 q.push(PosDist(p.x, p.y - 1, p.dist + 1));
  44.             }
  45.             if (p.y < m-1) {
  46.                 q.push(PosDist(p.x, p.y + 1, p.dist + 1));
  47.             }
  48.         }
  49.     }
  50.     return false;
  51. }
  52.  
  53. int main()
  54. {
  55.     int n, m;
  56.     cin >> n >> m;
  57.     MapaChar map(n, FilaChar(m));
  58.     for (int i = 0; i < n; i++) {
  59.         for (int j = 0; j < m; j++) {
  60.             cin >> map[i][j];
  61.         }
  62.     }
  63.     int f, c;
  64.     cin >> f >> c;
  65.     int dist = 0;
  66.     queue<PosDist> q;
  67.     q.push(PosDist(f-1, c-1, 0));
  68.     //MapaBool enq(n, FilaBool(m, false));
  69.     if (busca_tresor(map, n, m, dist, q)) {
  70.         cout << "distancia minima: " << dist << endl;
  71.     } else {
  72.         cout << "no es pot arribar a cap tresor" << endl;
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement