Problem · Dynamic Programming

Robot Survival Probability

Learn this problem
MediumInMobi logoInMobiFULLTIMEONSITE INTERVIEW

Problem statement

A robot starts at cell (startRow, startCol) on a rectangular grid with rows rows and cols columns. Rows and columns are zero-indexed.

At every step, the robot independently chooses one of four moves with equal probability: up, down, left, or right. If a move takes it outside the grid, the robot is destroyed immediately.

Return the probability that the robot is still on the grid after exactly steps moves.

Function

robotSurvivalProbability(rows: int, cols: int, startRow: int, startCol: int, steps: int) → double

Examples

Example 1

rows = 3cols = 3startRow = 1startCol = 1steps = 1return = 1.0

From the center of a 3-by-3 grid, all four one-step moves remain inside.

Example 2

rows = 3cols = 3startRow = 0startCol = 0steps = 1return = 0.5

From a corner, two of the four equally likely moves stay inside, so the survival probability is 2 / 4 = 0.5.

Example 3

rows = 2cols = 2startRow = 0startCol = 0steps = 2return = 0.25

The robot has probability 1 / 2 of surviving each move from any corner of this grid, so the two-step probability is 1 / 4.

Example 4

rows = 1cols = 1startRow = 0startCol = 0steps = 0return = 1.0

Before any move is made, the robot is still at its valid starting cell.

Constraints

  • 1 <= rows, cols <= 50
  • 0 <= startRow < rows
  • 0 <= startCol < cols
  • 0 <= steps <= 100
  • Answers within 10^-9 of the expected value are accepted.

More InMobi problems

drafts saved locally
public double robotSurvivalProbability(int rows, int cols, int startRow, int startCol, int steps) {
    // write your code here
}
rows3
cols3
startRow1
startCol1
steps1
expected1.0
checking account