Skip to content

2812. Find the Safest Path in a Grid

Description

You are given a 0-indexed 2D matrix grid of size n x n, where (r, c) represents:

  • A cell containing a thief if grid[r][c] = 1
  • An empty cell if grid[r][c] = 0

You are initially positioned at cell (0, 0). In one move, you can move to any adjacent cell in the grid, including cells containing thieves.

The safeness factor of a path on the grid is defined as the minimum manhattan distance from any cell in the path to any thief in the grid.

Return the maximum safeness factor of all paths leading to cell (n - 1, n - 1).

An adjacent cell of cell (r, c), is one of the cells (r, c + 1), (r, c - 1), (r + 1, c) and (r - 1, c) if it exists.

The Manhattan distance between two cells (a, b) and (x, y) is equal to |a - x| + |b - y|, where |val| denotes the absolute value of val.

 

Example 1:

Input: grid = [[1,0,0],[0,0,0],[0,0,1]]
Output: 0
Explanation: All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1).

Example 2:

Input: grid = [[0,0,1],[0,0,0],[0,0,0]]
Output: 2
Explanation: The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.

Example 3:

Input: grid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
Output: 2
Explanation: The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2.
- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.

 

Constraints:

  • 1 <= grid.length == n <= 400
  • grid[i].length == n
  • grid[i][j] is either 0 or 1.
  • There is at least one thief in the grid.

 

Solutions

Solution: Breadth-First Search

  • Time complexity: O(n2)
  • Space complexity: O(n2)

 

JavaScript

js
/**
 * @param {number[][]} grid
 * @return {number}
 */
const maximumSafenessFactor = function (grid) {
  const n = grid.length;
  const distances = new Array(n)
    .fill('')
    .map(_ => new Array(n).fill(Number.MAX_SAFE_INTEGER));
  const safeness = new Array(n)
    .fill('')
    .map(_ => new Array(n).fill(0));
  const moves = [
    [0, 1],
    [0, -1],
    [1, 0],
    [-1, 0],
  ];
  const isOutOfBounds = (row, col) => row >= n || col >= n || row < 0 || col < 0;
  let queue = [];

  for (let row = 0; row < n; row++) {
    for (let col = 0; col < n; col++) {
      if (!grid[row][col]) continue;
      distances[row][col] = 0;
      queue.push({ row, col });
    }
  }
  while (queue.length) {
    const nextQueue = [];

    for (const { row, col } of queue) {
      const distance = distances[row][col];

      for (const [moveRow, moveCol] of moves) {
        const nextRow = row + moveRow;
        const nextCol = col + moveCol;

        if (isOutOfBounds(nextRow, nextCol)) continue;
        if (distances[nextRow][nextCol] !== Number.MAX_SAFE_INTEGER) continue;
        distances[nextRow][nextCol] = distance + 1;
        nextQueue.push({ row: nextRow, col: nextCol });
      }
    }
    queue = nextQueue;
  }
  safeness[0][0] = distances[0][0];
  queue.push({ row: 0, col: 0 });

  while (queue.length) {
    const nextQueue = [];

    for (const { row, col } of queue) {
      for (const [moveRow, moveCol] of moves) {
        const nextRow = row + moveRow;
        const nextCol = col + moveCol;

        if (isOutOfBounds(nextRow, nextCol)) continue;
        const distance = Math.min(distances[nextRow][nextCol], safeness[row][col]);

        if (distance <= safeness[nextRow][nextCol]) continue;
        safeness[nextRow][nextCol] = distance;
        nextQueue.push({ row: nextRow, col: nextCol });
      }
    }
    queue = nextQueue;
  }
  return safeness[n - 1][n - 1];
};

Released under the MIT license