Advertisement
Alexvans

Dungeon Lvl.1

Jun 6th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define MAX 102
  3.  
  4. using namespace std;
  5.  
  6. int n, m;
  7. int cx, cy, px, py, lx, ly;
  8. char mat[MAX][MAX];
  9.  
  10. struct solve {
  11.     int x;
  12.     int y;
  13.     int d;
  14.     solve(int x1, int y1, int d1) : x(x1), y(y1), d(d1) {}
  15. };
  16.  
  17. bool norte(int x, int y) {
  18.     if((x-1) >= 0) return mat[x-1][y] != '*';
  19.     else return false;
  20. }
  21. bool sur(int x, int y) {
  22.     if((x+1) < n) return mat[x+1][y] != '*';
  23.     else return false;
  24. }
  25. bool este(int x, int y) {
  26.     if((y+1) < m) return mat[x][y+1] != '*';
  27.     else return false;
  28. }
  29. bool oeste(int x, int y) {
  30.     if((y-1) >= 0) return mat[x][y-1] != '*';
  31.     else return false;
  32. }
  33.  
  34. int bfs(int origenX, int origenY, int destinoX, int destinoY) {
  35.     bool v[MAX][MAX];
  36.     memset(v, false, sizeof(v));
  37.     solve ini(origenX, origenY, 0);
  38.     queue <solve> cola;
  39.     cola.push(ini);
  40.     while(!cola.empty()) {
  41.         solve now = cola.front();
  42.         cola.pop();
  43.         if(now.x == destinoX && now.y == destinoY) return now.d;
  44.         if(v[now.x][now.y]) continue;
  45.         v[now.x][now.y] = true;
  46.         if(norte(now.x, now.y)) {
  47.             solve r(now.x-1, now.y, now.d+1);
  48.             cola.push(r);
  49.         }
  50.         if(sur(now.x, now.y)) {
  51.             solve r(now.x+1, now.y, now.d+1);
  52.             cola.push(r);
  53.         }
  54.         if(este(now.x, now.y)) {
  55.             solve r(now.x, now.y+1, now.d+1);
  56.             cola.push(r);
  57.         }
  58.         if(oeste(now.x, now.y)) {
  59.             solve r(now.x, now.y-1, now.d+1);
  60.             cola.push(r);
  61.         }
  62.     }
  63.     return -1;
  64. }
  65.  
  66. int main() {
  67.     ios_base::sync_with_stdio(0);
  68.     cin.tie(0);
  69.     cout.tie(0);
  70.  
  71.     cin >> n >> m;
  72.     for(int i = 0; i < n; i++) {
  73.         for(int j = 0; j < m; j++) {
  74.             cin >> mat[i][j];
  75.             if(mat[i][j] == 'c') cx = i, cy = j;
  76.             if(mat[i][j] == 'p') px = i, py = j;
  77.             if(mat[i][j] == 'l') lx = i, ly = j;
  78.         }
  79.     }
  80.     int r1 = bfs(cx, cy, lx, ly);
  81.     int r2 = bfs(lx, ly, px, py);
  82.     if(r1 != -1 && r2 != -1) cout << r1 + r2;
  83.     else cout << -1;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement