Problem · Matrix
MediumGoldman Sachs logoGoldman SachsFULLTIMEONSITE INTERVIEW

Problem statement

A ball is placed in a rectangular maze represented by a binary matrix. Empty cells contain 0 and walls contain 1. The ball can move up, down, left, or right, but it keeps rolling in the chosen direction until a wall stops it.

Given the ball's start and destination cells, return true if the ball can stop at the destination and false otherwise.

Function

hasPath(maze: int[][], start: int[], destination: int[]) → boolean

Examples

Example 1

maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]start = [0,4]destination = [4,4]return = true

A sequence of rolls can stop the ball at the destination.

Example 2

maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]start = [0,4]destination = [3,2]return = false

The ball can pass through the destination cell but cannot stop there.

Constraints

  • 1 <= maze.length, maze[0].length <= 100
  • maze[i][j] is either 0 or 1.
  • start and destination each contain two coordinates.
  • The start and destination cells are empty.
  • The maze is surrounded by walls outside its boundary.

More Goldman Sachs problems

drafts saved locally
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
    // Write your code here
}
maze[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]
start[0,4]
destination[4,4]
expectedtrue
checking account