Problem Β· Graph

Converging Maze: Nearest meeting cell

Learn this problem
● MediumJuspayNEW GRADOA

Problem statement

You are given a maze with N cells. Each cell may have multiple entry points but not more than one exit (ie. entry/exit points are unidirectional doors like valves). The cells are named with an integer value from 0 to N-1.

You have to find:

Nearest meeting cell: Given any two cells, src and dest, find a cell that can be reached from both. For each common reachable cell, consider the larger of its distances from src and dest. Return the cell that minimizes this distance. If multiple cells are tied, return the cell with the smallest number. Return -1 when no cell is reachable from both starts.

Function

nearestMeetingCell(arr: int[], src: int, dest: int) β†’ int

Complete nearestMeetingCell with the following parameters:

  • int[] arr: an array of length N, where arr[i] is the cell reached from cell i in one step, or -1 when cell i has no exit. The value of N is arr.length.
  • int src: the first starting cell
  • int dest: the second starting cell

Returns

int: the nearest meeting cell, or -1 if no meeting cell exists

πŸ€ Endless thanks to the friend who generously helped!

Examples

Example 1

arr = [4, 4, 1, 4, 13, 8, 8, 8, 0, 8, 14, 9, 15, 11, -1, 10, 15, 22, 22, 22, 22, 22, 21]src = 9dest = 2return = 4
Starting from cell 9 reaches 9 β†’ 8 β†’ 0 β†’ 4, while starting from cell 2 reaches 2 β†’ 1 β†’ 4. Cell 4 is the closest cell reachable from both starts.

Constraints

  • 1 ≤ arr.length ≤ 105
  • -1 ≤ arr[i] < arr.length
  • 0 ≤ src, dest < arr.length

More Juspay problems

drafts saved locally
public int nearestMeetingCell(int[] arr, int src, int dest) {
  // write your code here
}
arr[4, 4, 1, 4, 13, 8, 8, 8, 0, 8, 14, 9, 15, 11, -1, 10, 15, 22, 22, 22, 22, 22, 21]
src9
dest2
expected4
checking account