Approach
Breadth-first search
For Minimum Path Cost in a Hidden 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
- 75 lines of Java from the credited upstream file 1810.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.
1/**2 * 3 * 4 * class GridMaster {5 * boolean canMove(char direction);6 * int move(char direction);7 * boolean isTarget();8 * }9 */10 11class Solution {12 public int findShortestPath(GridMaster master) {13 final int m = 100;14 final int startX = m;15 final int startY = m;16 int[] target = {m * 2, m * 2};17 int[][] grid = new int[m * 2][m * 2];18 boolean[][] seen = new boolean[m * 2][m * 2];19 Arrays.stream(grid).forEach(A -> Arrays.fill(A, -1));20 21 22 dfs(master, grid, startX, startY, target);23 24 Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[2])) {25 { offer(new int[] {startX, startY, 0}); }26 };27 28 29 while (!minHeap.isEmpty()) {30 final int i = minHeap.peek()[0];31 final int j = minHeap.peek()[1];32 final int cost = minHeap.poll()[2];33 if (i == target[0] && j == target[1])34 return cost;35 if (seen[i][j])36 continue;37 seen[i][j] = true;38 for (int[] dir : DIRS) {39 final int x = i + dir[0];40 final int y = j + dir[1];41 if (x < 0 || x == 2 * m || y < 0 || y == 2 * m)42 continue;43 if (seen[x][y] || grid[x][y] == -1)44 continue;45 final int nextCost = cost + grid[x][y];46 minHeap.offer(new int[] {x, y, nextCost});47 }48 }49 50 return -1;51 }52 53 private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};54 private static final char[] charTable = {'R', 'D', 'L', 'U'};55 56 private void dfs(GridMaster master, int[][] grid, int i, int j, int[] target) {57 if (master.isTarget()) {58 target[0] = i;59 target[1] = j;60 }61 62 for (int k = 0; k < 4; ++k) {63 final int x = i + DIRS[k][0];64 final int y = j + DIRS[k][1];65 final char d = charTable[k];66 final char undoD = charTable[(k + 2) % 4];67 if (master.canMove(d) && grid[x][y] == -1) {68 grid[x][y] = master.move(d);69 dfs(master, grid, x, y, target);70 master.move(undoD);71 }72 }73 }74}75