Approach
Breadth-first search
For Minimum Cost to Make at Least One Valid Path in a Grid, 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
- 38 lines of C++ from the credited upstream file 1368.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected, together with recursive traversal.
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 minCost(vector<vector<int>>& grid) {4 const int m = grid.size();5 const int n = grid[0].size();6 vector<vector<int>> mem(m, vector<int>(n, -1));7 queue<pair<int, int>> q;8 9 dfs(grid, 0, 0, 0, q, mem);10 11 for (int cost = 1; !q.empty(); ++cost)12 for (int sz = q.size(); sz > 0; --sz) {13 const auto [i, j] = q.front();14 q.pop();15 for (const auto& [dx, dy] : kDirs)16 dfs(grid, i + dx, j + dy, cost, q, mem);17 }18 19 return mem.back().back();20 }21 22 private:23 static constexpr int kDirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};24 25 void dfs(const vector<vector<int>>& grid, int i, int j, int cost,26 queue<pair<int, int>>& q, vector<vector<int>>& mem) {27 if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size())28 return;29 if (mem[i][j] != -1)30 return;31 32 mem[i][j] = cost;33 q.emplace(i, j);34 const auto& [dx, dy] = kDirs[grid[i][j] - 1];35 dfs(grid, i + dx, j + dy, cost, q, mem);36 }37};38