Advertisement
JosepRivaille

P39846: Tresors en un mapa (4)

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