Advertisement
Alex_tz307

TopCoder Desert Wind

Apr 5th, 2021
800
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. /// https://arena.topcoder.com/index.html#/u/practiceCode/1289/1468/1570/1/1289
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. class DesertWind {
  7.   public:
  8.     int daysNeeded(vector<string> theMap) {
  9.       int N = theMap.size(), M = theMap[0].size();
  10.       const int INF = 0x3f3f3f3f;
  11.       const int di[] = {-1, 0, 1, 0, -1, -1, 1, 1}, dj[] = {0, 1, 0, -1, -1, 1, -1, 1};
  12.       vector<vector<int>> dp(N, vector<int>(M, INF));
  13.       int goal_x = -1, goal_y = -1;
  14.       for (int i = 0; i < N; ++i)
  15.         for (int j = 0; j < M; ++j)
  16.           if (theMap[i][j] == '@')
  17.             goal_x = i, goal_y = j;
  18.           else
  19.             if (theMap[i][j] == '*')
  20.               dp[i][j] = 0;
  21.       auto inside = [&](int l, int c) -> bool {
  22.         return l >= 0 && c >= 0 && l < N && c < M;
  23.       };
  24.       bool ok = true;
  25.       while (ok) {
  26.         ok = false;
  27.         for (int i = 0; i < N; ++i)
  28.           for (int j = 0; j < M; ++j)
  29.             if (theMap[i][j] != 'X') {
  30.               int best1 = INF, best2 = INF;
  31.               for (int k = 0; k < 8; ++k) {
  32.                 int iv = i + di[k], jv = j + dj[k];
  33.                 if (!inside(iv, jv))
  34.                   continue;
  35.                 int cost = dp[iv][jv] + 1;
  36.                 if (cost <= best1) {
  37.                   best2 = best1;
  38.                   best1 = cost;
  39.                 } else {
  40.                   if (cost < best2)
  41.                     best2 = cost;
  42.                 }
  43.               }
  44.               int best_cost = min(best1 + 2, best2);
  45.               if (best_cost < dp[i][j]) {
  46.                 dp[i][j] = best_cost;
  47.                 ok = true;
  48.               }
  49.             }
  50.       }
  51.       if (dp[goal_x][goal_y] == INF)
  52.         return -1;
  53.       return dp[goal_x][goal_y];
  54.     }
  55. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement