JosepRivaille

P60796: Tresors en un mapa (2)

Apr 30th, 2016
1,459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <stack>
  5. using namespace std;
  6.  
  7. typedef vector<char> Row;
  8. typedef vector<Row> Graph;
  9.  
  10.  
  11. int bfs(const Graph &G, int xx, int yy)
  12. {
  13.   Graph visited(G.size(), Row(G[0].size(), 'F'));
  14.   queue< pair<int, int> >  Q;
  15.   queue<int> dQ;
  16.   Q.push(make_pair(xx, yy));
  17.   dQ.push(0);
  18.   visited[xx][yy] = 'T';
  19.   while (!Q.empty()) {
  20.     pair<int, int> actual = Q.front();
  21.     int x = actual.first;
  22.     int y = actual.second;
  23.     int dist = dQ.front() + 1;
  24.     //Above
  25.     if (y > 0 && visited[x][y-1] == 'F' && G[x][y-1] != 'X') {
  26.       if (G[x][y-1] == 't') return dist;
  27.       Q.push(make_pair(x, y-1));
  28.       dQ.push(dist);
  29.       visited[x][y-1] = 'T';
  30.     }
  31.     //Below
  32.     if (y < G[0].size() - 1 && visited[x][y+1] == 'F' && G[x][y+1] != 'X') {
  33.       if (G[x][y+1] == 't') return dist;
  34.       Q.push(make_pair(x, y+1));
  35.       dQ.push(dist);
  36.       visited[x][y+1] = 'T';
  37.     }
  38.     //Left
  39.     if (x > 0 && visited[x-1][y] == 'F' && G[x-1][y] != 'X') {
  40.       if (G[x-1][y] == 't') return dist;
  41.       Q.push(make_pair(x-1, y));
  42.       dQ.push(dist);
  43.       visited[x-1][y] = 'T';
  44.     }
  45.     //Right
  46.     if (x < G.size() - 1 && visited[x+1][y] == 'F' && G[x+1][y] != 'X') {
  47.       if (G[x+1][y] == 't') return dist;
  48.       Q.push(make_pair(x+1, y));
  49.       dQ.push(dist);
  50.       visited[x+1][y] = 'T';
  51.     }
  52.     Q.pop();
  53.     dQ.pop();
  54.   }
  55.   //No vertexes found
  56.   return -1;
  57. }
  58.  
  59. int main()
  60. {
  61.   int n, m;
  62.   cin >> n >> m;
  63.   Graph G(n, Row(m));
  64.   for (int i = 0; i < n; ++i)
  65.     for (int j = 0; j < m; ++j)
  66.       cin >> G[i][j];
  67.   int x, y;
  68.   cin >> x >> y;
  69.   int res = bfs(G, x-1, y-1);
  70.   if (res < 0) cout << "no es pot arribar a cap tresor" << endl;
  71.   else cout << "distancia minima: " << res << endl;
  72. }
  73.  
  74. //JosepRivaille
Advertisement
Add Comment
Please, Sign In to add comment