Table of Contents
Problem Statement
You are given a 0-indexed 2D integer array grid
of size m x n
which represents a field. Each cell has one of three values:
0
represents grass,1
represents fire,2
represents a wall that you and fire cannot pass through.
You are situated in the top-left cell, (0, 0)
, and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1)
. Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls.
Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return -1
. If you can always reach the safehouse regardless of the minutes stayed, return 109
.
Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse.
A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).
Example 1:
Input: grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]] Output: 3 Explanation: The figure above shows the scenario where you stay in the initial position for 3 minutes. You will still be able to safely reach the safehouse. Staying for more than 3 minutes will not allow you to safely reach the safehouse.
Example 2:
Input: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]] Output: -1 Explanation: The figure above shows the scenario where you immediately move towards the safehouse. Fire will spread to any cell you move towards and it is impossible to safely reach the safehouse. Thus, -1 is returned.
Example 3:
Input: grid = [[0,0,0],[2,2,0],[1,2,0]] Output: 1000000000 Explanation: The figure above shows the initial grid. Notice that the fire is contained by walls and you will always be able to safely reach the safehouse. Thus, 109 is returned.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 300
4 <= m * n <= 2 * 104
grid[i][j]
is either0
,1
, or2
.grid[0][0] == grid[m - 1][n - 1] == 0
Golang Code
package main
import (
"fmt"
"math"
)
type pair struct {
row, col int
}
// BFS function for fire spread
func bfsFire(grid [][]int, timeGrid [][]int, totalRow, totalCol int) {
queue := []pair{}
// Initialize fire sources in the queue and set time as 0 in timeGrid
for i := 0; i < totalRow; i++ {
for j := 0; j < totalCol; j++ {
if grid[i][j] == 1 { // fire source
queue = append(queue, pair{i, j})
timeGrid[i][j] = 0
}
}
}
// Directions for moving up, down, left, and right
directions := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
// BFS to update timeGrid with fire spread times
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
currentTime := timeGrid[current.row][current.col]
for _, dir := range directions {
newRow, newCol := current.row+dir[0], current.col+dir[1]
if newRow >= 0 && newRow < totalRow && newCol >= 0 && newCol < totalCol &&
grid[newRow][newCol] == 0 && timeGrid[newRow][newCol] == math.MaxInt32 {
timeGrid[newRow][newCol] = currentTime + 1
queue = append(queue, pair{newRow, newCol})
}
}
}
}
// BFS for person's path calculation with fire timing constraint
func bfsPerson(grid, timeGrid [][]int, totalRow, totalCol int) int {
queue := []pair{{0, 0}}
personTimeGrid := make([][]int, totalRow)
for i := range personTimeGrid {
personTimeGrid[i] = make([]int, totalCol)
for j := range personTimeGrid[i] {
personTimeGrid[i][j] = math.MaxInt32
}
}
personTimeGrid[0][0] = 0
directions := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
// BFS to calculate person’s shortest path while avoiding fire
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
currentTime := personTimeGrid[current.row][current.col]
for _, dir := range directions {
newRow, newCol := current.row+dir[0], current.col+dir[1]
if newRow >= 0 && newRow < totalRow && newCol >= 0 && newCol < totalCol &&
grid[newRow][newCol] == 0 && currentTime+1 < personTimeGrid[newRow][newCol] &&
currentTime+1 < timeGrid[newRow][newCol] {
personTimeGrid[newRow][newCol] = currentTime + 1
queue = append(queue, pair{newRow, newCol})
}
}
}
finalTime := personTimeGrid[totalRow-1][totalCol-1]
fireTimeAtSafehouse := timeGrid[totalRow-1][totalCol-1]
if finalTime == math.MaxInt32 {
return -1 // Safehouse unreachable
} else if fireTimeAtSafehouse == math.MaxInt32 {
return 1e9 // Fire never reaches safehouse
} else if finalTime < fireTimeAtSafehouse {
return fireTimeAtSafehouse - finalTime - 1
}
return -1
}
func maximumMinutes(grid [][]int) int {
totalRow := len(grid)
totalCol := len(grid[0])
timeGrid := make([][]int, totalRow)
for i := range timeGrid {
timeGrid[i] = make([]int, totalCol)
for j := range timeGrid[i] {
timeGrid[i][j] = math.MaxInt32
}
}
// Step 1: BFS for fire to populate timeGrid
bfsFire(grid, timeGrid, totalRow, totalCol)
// Step 2: BFS for person and calculate the maximum safe delay time
return bfsPerson(grid, timeGrid, totalRow, totalCol)
}
func main() {
grid := [][]int{
{0, 0, 0},
{0, 1, 0},
{0, 0, 0},
}
fmt.Println(maximumMinutes(grid))
}
Output
grid := [][]int{
{0, 2, 0, 0, 0, 0, 0},
{0, 0, 0, 2, 2, 1, 0},
{0, 2, 0, 0, 1, 2, 0},
{0, 0, 2, 2, 2, 0, 2},
{0, 0, 0, 0, 0, 0, 0},
}
Output
3
==========================================
grid := [][]int{
{0, 0, 0, 0},
{0, 1, 2, 0},
{0, 2, 0, 0},
}
Output
-1
==========================================
grid := [][]int{
{0, 0, 0},
{2, 2, 0},
{1, 2, 0},
}
Output
1000000000
==========================================
Leave a Reply