The Maze III

HardGraphsdijkstra

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A ball sits in a grid maze where 0 is an empty cell and 1 is a wall; the area outside the grid also acts as a wall. The ball can be pushed 'u' (up), 'd' (down), 'l' (left) or 'r' (right). Once pushed, it keeps rolling through empty cells until the next cell in that direction is a wall, and then it stops. There is a hole in the maze: if the ball rolls **onto** the hole, it drops in immediately, even mid-roll. Given maze, the ball's start ball = [row, col] and the hole hole = [row, col], return the sequence of pushes that gets the ball into the hole while traveling the **shortest distance**. Distance is the number of empty cells the ball passes through, counting the cell it ends on and not the start. If several push sequences reach the hole with that same shortest distance, return the **lexicographically smallest** string among them. If the ball can never drop into the hole, return "impossible".

Examples

Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [0,1]
Output: "lul"
`lul` travels 1 + 4 + 1 = 6 cells and `ul` travels 4 + 2 = 6 cells. Both are shortest, and `lul` is lexicographically smaller.
Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [3,0]
Output: "impossible"
No push sequence makes the ball stop on or roll across (3, 0).
Input: maze = [[0,0,0,0,0,0,0],[0,0,1,0,0,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,1]], ball = [0,4], hole = [3,5]
Output: "dldr"
Down, left, down, right reaches the hole with the fewest cells traveled.

Constraints

  • m == maze.length, n == maze[i].length
  • 1 <= m, n <= 100
  • maze[i][j] is 0 or 1
  • `ball` and `hole` are empty cells and are different

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dijkstra problems