Approach
Breadth-first search
For Shortest Path 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
- 73 lines of Java from the credited upstream file 1778.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 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 * void move(char direction);7 * boolean isTarget();8 * }9 */10 11enum Grid { UNVISITED, START, TARGET, BLOCKED, EMPTY }12 13class Solution {14 public int findShortestPath(GridMaster master) {15 final int m = 501;16 final int startX = m;17 final int startY = m;18 Grid[][] grid = new Grid[m * 2][m * 2];19 Arrays.stream(grid).forEach(A -> Arrays.fill(A, Grid.UNVISITED));20 21 22 dfs(master, grid, startX, startY);23 24 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(startX, startY)));25 grid[startX][startY] = Grid.BLOCKED;26 27 28 for (int step = 1; !q.isEmpty(); ++step)29 for (int sz = q.size(); sz > 0; --sz) {30 final int i = q.peek().getKey();31 final int j = q.poll().getValue();32 for (int[] dir : DIRS) {33 final int x = i + dir[0];34 final int y = j + dir[1];35 if (grid[x][y] == Grid.TARGET)36 return step;37 if (grid[x][y] == Grid.BLOCKED)38 continue;39 grid[x][y] = Grid.BLOCKED;40 q.offer(new Pair<>(x, y));41 }42 }43 44 return -1;45 }46 47 private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};48 private static final char[] charTable = {'R', 'D', 'L', 'U'};49 50 private void dfs(GridMaster master, Grid[][] grid, int i, int j) {51 if (grid[i][j] != Grid.UNVISITED)52 return;53 if (master.isTarget())54 grid[i][j] = Grid.TARGET;55 else56 grid[i][j] = Grid.EMPTY;57 58 for (int k = 0; k < 4; ++k) {59 final int x = i + DIRS[k][0];60 final int y = j + DIRS[k][1];61 final char d = charTable[k];62 final char undoD = charTable[(k + 2) % 4];63 if (master.canMove(d)) {64 master.move(d);65 dfs(master, grid, x, y);66 master.move(undoD);67 } else {68 grid[x][y] = Grid.BLOCKED;69 }70 }71 }72}73