Advertisement
JosepRivaille

P43164: Tresors en un mapa (5)

May 19th, 2016
469
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <stack>
  5. using namespace std;
  6.  
  7. typedef pair<int, int> Pos;
  8. typedef int boolean;
  9. typedef vector<boolean> Row;
  10. typedef vector<Row> Graph;
  11. typedef vector<char> Row2;
  12. typedef vector<Row2> Matrix;
  13.  
  14.  
  15. void bfs(Matrix &M, int x, int y)
  16. {
  17.   Graph distance(M.size(), Row(M[0].size(), 0));
  18.   Graph visited(M.size(), Row(M[0].size(), false));
  19.   queue<Pos> Q;
  20.   stack<int> max_distances;
  21.   Q.push(make_pair(x, y));
  22.   while (!Q.empty()) {
  23.     Pos new_pos = Q.front(); Q.pop();
  24.     int i = new_pos.first;
  25.     int j = new_pos.second;
  26.     if (M[i][j] == 't') max_distances.push(distance[i][j]);
  27.     //Add new nodes
  28.     //Above
  29.     if (i > 0 && !visited[i-1][j]) {
  30.       visited[i-1][j] = true;
  31.       if (M[i-1][j] != 'X') {
  32.     distance[i-1][j] = distance[i][j] + 1;
  33.     Q.push(make_pair(i-1, j));
  34.       }
  35.     }
  36.     //Below
  37.     if (i < M.size()-1 && !visited[i+1][j]) {
  38.       visited[i+1][j] = true;
  39.       if (M[i+1][j] != 'X') {
  40.     distance[i+1][j] = distance[i][j] + 1;
  41.     Q.push(make_pair(i+1, j));
  42.       }
  43.     }
  44.     //Left
  45.     if (j > 0 && !visited[i][j-1]) {
  46.       visited[i][j-1] = true;
  47.       if (M[i][j-1] != 'X') {
  48.     distance[i][j-1] = distance[i][j] + 1;
  49.     Q.push(make_pair(i, j-1));
  50.       }
  51.     }
  52.     //Right
  53.     if (j < M[0].size()-1 && !visited[i][j+1]) {
  54.       visited[i][j+1] = true;
  55.       if (M[i][j+1] != 'X') {
  56.     distance[i][j+1] = distance[i][j] + 1;
  57.     Q.push(make_pair(i, j+1));
  58.       }
  59.     }
  60.   }
  61.   if (max_distances.empty()) cout << "no es pot arribar a dos o mes tresors" << endl;
  62.   else {
  63.     max_distances.pop();
  64.     if (max_distances.empty()) cout << "no es pot arribar a dos o mes tresors" << endl;
  65.     else cout << "segona distancia maxima: " << max_distances.top() << endl;
  66.   }
  67. }
  68.  
  69. int main()
  70. {
  71.   int n, m, x, y;
  72.   cin >> n >> m;
  73.   Matrix M(n, Row2(m));
  74.   for (int i = 0; i < n; ++i) {
  75.     for (int j = 0; j < m; ++j) {
  76.       cin >> M[i][j];
  77.     }
  78.   }
  79.   cin >> x >> y;
  80.   bfs(M, x-1, y-1);
  81. }
  82.  
  83. //JosepRivaille
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement