Problem · Hash Table

Can Reach the Exit with Teleports

Learn this problem
MediumTiktokNEW GRADINTERNOA
See Tiktok hiring insights

Problem statement

You are exploring a rectangular labyrinth with n rows and m columns. You start in the upper-left cell (0, 0), and your goal is to reach the exit in the lower-right cell (n - 1, m - 1).

The labyrinth contains obstacles and one-way teleports:

  • Each element of obstacles is [row, col]. You cannot enter an obstacle cell. If your next move would enter one, you stop and cannot reach the exit.
  • Each element of teleports is [startRow, startCol, endRow, endCol]. Whenever you occupy a teleport's start cell, you immediately move to its end cell.
  • Teleportation does not work backward. Every teleport start is unique, no teleport end is another teleport start, and neither endpoint is an obstacle.
  • Any other cell is free.

At every free cell, you try to move one column to the right, from (row, col) to (row, col + 1). A teleport may move you to any valid cell, including a cell in another row or an earlier column. The same movement rules then continue from the destination.

Return true if this deterministic process reaches the exit. Return false if you encounter an obstacle, leave the grid before reaching the exit, or revisit a cell and therefore enter a loop.

The starting cell is processed by the same rules. Reaching the exit succeeds immediately, before applying any further movement.

Function

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

Examples

Example 1

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

The path is (0,0) → (0,1) → (2,1) → (2,2) → (2,3). Entering (0,1) triggers the teleport, and the process then reaches the exit.

Example 2

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

The teleport moves you from (0,1) to (2,0). The next cell, (2,1), is an obstacle, so movement stops before the exit.

Example 3

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

Moving right reaches (0,1), which teleports back to (0,0). Because the process repeats the same cells forever, it cannot reach the exit.

More Tiktok problems

drafts saved locally
public boolean canReachExit(int n, int m, int[][] obstacles, int[][] teleports) {
    // write your code here
}
n3
m4
obstacles[]
teleports[[0,1,2,1]]
expectedtrue
checking account