Leetcode 2812: Find the Safest Path in a Grid

grid47
grid47
Exploring patterns and algorithms
Jan 30, 2024 8 min read

You are given a square grid of size n x n, where each cell contains either a thief (represented by 1) or is empty (represented by 0). You start at the top-left corner of the grid and must find the maximum safeness factor for a path to the bottom-right corner. The safeness factor is defined as the minimum Manhattan distance from any cell in the path to the nearest thief.
Problem
Approach
Steps
Complexity
Input: The input consists of a grid, where each cell is either 0 or 1. A 0 indicates an empty cell, and a 1 indicates a cell with a thief.
Example: grid = [[0, 0, 1], [0, 0, 0], [0, 0, 0]]
Constraints:
• 1 <= n <= 400
• grid[i][j] is either 0 or 1
• There is at least one thief in the grid.
Output: Return the maximum safeness factor of all paths leading to cell (n-1, n-1).
Example: Output: 2
Constraints:
• The safeness factor is an integer value.
Goal: The goal is to find the maximum safeness factor for any path to the bottom-right corner of the grid.
Steps:
• Initialize a queue and push the positions of all thieves in the grid.
• Use a breadth-first search (BFS) to calculate the minimum distance from each cell to the nearest thief.
• Use a priority queue to find the path from the top-left to the bottom-right corner while maximizing the safeness factor.
• Return the maximum safeness factor from the top of the priority queue.
Goal: Constraints regarding the grid size and values.
Steps:
• 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.
Assumptions:
• The grid is square, and at least one thief is present.
Input: Example 1
Explanation: All paths from (0, 0) to (n-1, n-1) go through thieves, resulting in a safeness factor of 0.

Input: Example 2
Explanation: The safeness factor is calculated as the minimum Manhattan distance from the path to the nearest thief.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus