Problem · Matrix

Grid Walk with Obstacles and Teleports

Learn this problem
MediumVisa logoVisaNEW GRADOA

Problem statement

You are given an n by m grid. Its rows and columns use zero-based coordinates. Starting at (0,0), follow a deterministic walk toward (n-1,m-1).

Each entry [r,c] in obstacles marks a cell that cannot be entered. Each entry [sr,sc,er,ec] in teleports is a directed teleport from (sr,sc) to (er,ec).

  1. Count the starting cell as the first visited cell.
  2. When you enter a teleport entrance, immediately move to its exit. Count both the entrance and exit as visited cells. The teleport takes priority over an ordinary move.
  3. From any other non-goal cell, move one cell to the right if that cell is inside the grid and is not an obstacle.
  4. Only if the right move is unavailable, try one cell downward. If neither move is available, the walk ends at a dead end.

Return the number of visited cells when the walk reaches the bottom-right cell. Return -1 if it reaches a dead end before the goal, or -2 if the walk repeats forever because of teleports. Do not choose alternative routes or backtrack.

The start and goal are never obstacles or teleport endpoints. All teleport endpoints are distinct from one another, and no teleport endpoint is an obstacle. Each teleport has different entrance and exit cells.

Function

solution(n: int, m: int, obstacles: int[][], teleports: int[][]) → int

Examples

Example 1

n = 3m = 4obstacles = [[2,0],[1,0]]teleports = [[0,1,1,1],[1,2,0,2],[0,3,2,1]]return = 9

The visited cells are (0,0), (0,1), (1,1), (1,2), (0,2), (0,3), (2,1), (2,2), (2,3). The starting cell and both endpoints of each teleport are included, so the answer is 9.

Example 2

n = 2m = 3obstacles = [[0,2],[1,1]]teleports = []return = -1

The walk goes from (0,0) to (0,1). Its right and lower neighbors are both obstacles, so it stops at a dead end. It does not backtrack to try a different route.

Example 3

n = 2m = 4obstacles = []teleports = [[0,2,0,1]]return = -2

The walk visits (0,0), (0,1), (0,2) and teleports back to (0,1). It repeats the same movement forever, so return -2.

Constraints

  • 1 <= n, m <= 1000 and n * m <= 10^6.
  • All coordinates are valid integer grid coordinates.
  • Obstacle cells are distinct. Teleport endpoints are pairwise distinct and do not overlap obstacles.
  • (0,0) and (n-1,m-1) are neither obstacles nor teleport endpoints.
  • obstacles and teleports may be empty.

More Visa problems

drafts saved locally
public int solution(int n, int m, int[][] obstacles, int[][] teleports) {
    // Write your code here.
}
n3
m4
obstacles[[2,0],[1,0]]
teleports[[0,1,1,1],[1,2,0,2],[0,3,2,1]]
expected9
checking account