Approach
Breadth-first search
For Minimum Time Takes to Reach Destination Without Drowning, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 75 lines of C++ from the credited upstream file 2814.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 10 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int minimumSeconds(vector<vector<string>>& land) {4 const int m = land.size();5 const int n = land[0].size();6 const vector<vector<int>> floodDist = getFloodDist(land);7 queue<pair<int, int>> q;8 vector<vector<bool>> seen(m, vector<bool>(n));9 10 for (int i = 0; i < m; ++i)11 for (int j = 0; j < n; ++j)12 if (land[i][j] == "S") {13 q.emplace(i, j);14 seen[i][j] = true;15 }16 17 for (int step = 1; !q.empty(); ++step)18 for (int sz = q.size(); sz > 0; --sz) {19 const auto [i, j] = q.front();20 q.pop();21 for (const auto& [dx, dy] : kDirs) {22 const int x = i + dx;23 const int y = j + dy;24 if (x < 0 || x == m || y < 0 || y == n)25 continue;26 if (land[x][y] == "D")27 return step;28 if (floodDist[x][y] <= step || land[x][y] == "X" || seen[x][y])29 continue;30 q.emplace(x, y);31 seen[x][y] = true;32 }33 }34 35 return -1;36 }37 38 private:39 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};40 41 vector<vector<int>> getFloodDist(const vector<vector<string>>& land) {42 const int m = land.size();43 const int n = land[0].size();44 vector<vector<int>> dist(m, vector<int>(n, INT_MAX));45 queue<pair<int, int>> q;46 vector<vector<bool>> seen(m, vector<bool>(n));47 48 for (int i = 0; i < m; ++i)49 for (int j = 0; j < n; ++j)50 if (land[i][j] == "*") {51 q.emplace(i, j);52 seen[i][j] = true;53 }54 55 for (int d = 0; !q.empty(); ++d)56 for (int sz = q.size(); sz > 0; --sz) {57 const auto [i, j] = q.front();58 q.pop();59 dist[i][j] = d;60 for (const auto& [dx, dy] : kDirs) {61 const int x = i + dx;62 const int y = j + dy;63 if (x < 0 || x == m || y < 0 || y == n)64 continue;65 if (land[x][y] == "X" || land[x][y] == "D" || seen[x][y])66 continue;67 q.emplace(x, y);68 seen[x][y] = true;69 }70 }71 72 return dist;73 }74};75