Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1778. Shortest Path in a Hidden Grid

Explanation:

The problem requires finding the shortest path in a hidden grid. Each cell in the grid can be either empty or blocked. We can move in four directions - up, down, left, or right. The hidden grid is represented by an interface GridMaster with the following methods:

  • boolean canMove(char direction): Returns true if we can move in the specified direction.
  • void move(char direction): Moves in the specified direction.
  • boolean isTarget(): Returns true if the current cell is the target cell.

To solve this problem, we can use backtracking along with DFS to explore all possible paths from the starting cell to the target cell. We can keep track of visited cells to avoid revisiting the same cell and ensure that we find the shortest path.

: :

interface GridMaster {
    boolean canMove(char direction);
    void move(char direction);
    boolean isTarget();
}

class Solution {
    public int findShortestPath(GridMaster master) {
        int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        Map<Integer, Integer> visited = new HashMap<>();
        visited.put(0, 0);
        int[] start = {0, 0};
        dfs(master, start, dirs, visited);
        return visited.getOrDefault(1, -1);
    }

    private void dfs(GridMaster master, int[] curr, int[][] dirs, Map<Integer, Integer> visited) {
        if (master.isTarget()) {
            visited.put(1, visited.get(curr[0] * 1000 + curr[1]) + 1);
            return;
        }
        for (int i = 0; i < 4; i++) {
            int newX = curr[0] + dirs[i][0];
            int newY = curr[1] + dirs[i][1];
            if (!visited.containsKey(newX * 1000 + newY) && master.canMove(getDirection(i))) {
                visited.put(newX * 1000 + newY, visited.get(curr[0] * 1000 + curr[1]) + 1);
                master.move(getDirection(i));
                dfs(master, new int[]{newX, newY}, dirs, visited);
                master.move(getDirection((i + 2) % 4)); // Move back
            }
        }
    }

    private char getDirection(int i) {
        return i == 0 ? 'R' : i == 1 ? 'L' : i == 2 ? 'D' : 'U';
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.