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 Java from the credited upstream file 1368.java.
- 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 int minCost(int[][] grid) {3 final int m = grid.length;4 final int n = grid[0].length;5 int[][] mem = new int[m][n];6 Arrays.stream(mem).forEach(A -> Arrays.fill(A, -1));7 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>();8 9 dfs(grid, 0, 0, 0, q, mem);10 11 for (int cost = 1; !q.isEmpty(); ++cost)12 for (int sz = q.size(); sz > 0; --sz) {13 Pair<Integer, Integer> pair = q.poll();14 final int i = pair.getKey();15 final int j = pair.getValue();16 for (int[] dir : DIRS)17 dfs(grid, i + dir[0], j + dir[1], cost, q, mem);18 }19 20 return mem[m - 1][n - 1];21 }22 23 private static final int[][] DIRS = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};24 25 private void dfs(int[][] grid, int i, int j, int cost, Queue<Pair<Integer, Integer>> q,26 int[][] mem) {27 if (i < 0 || i == grid.length || j < 0 || j == grid[0].length)28 return;29 if (mem[i][j] != -1)30 return;31 32 mem[i][j] = cost;33 q.add(new Pair<>(i, j));34 int[] dir = DIRS[grid[i][j] - 1];35 dfs(grid, i + dir[0], j + dir[1], cost, q, mem);36 }37}38