Program to check person can reach top-left or bottomright cell avoiding fire or not in Python

Suppose we have a 2D matrix with few different values like below ?

  • 0 for empty cell

  • 1 for a person

  • 2 for fire

  • 3 for a wall

Now assume there is only one person and in each turn the fire expands in all four directions (up, down, left and right) but fire cannot expand through walls. We have to check whether the person can move to either the top-left corner or the bottom-right corner of the matrix. We have to keep in mind that in each turn, the person moves first, then the fire expands. If the person makes it to any of the target cells at the same time as the fire, then he is safe.

Example Input

So, if the input is like ?

0 0 0
0 0 1
0 0 2

then the output will be True, as the person can go to the top left corner.

Algorithm Approach

To solve this, we will follow these steps ?

  • Use BFS to calculate the minimum distance for fire to reach each cell

  • Use BFS to calculate the minimum distance for person to reach each cell

  • Check if person can reach top-left (0,0) or bottom-right corner before fire

  • Person is safe if they reach the target cell at the same time or before fire

Implementation

from collections import deque

class Solution:
    def solve(self, A):
        INF = int(1e9)
        R, C = len(A), len(A[0])
        
        def get_neighbors(r, c):
            for nr, nc in [[r - 1, c], [r, c - 1], [r + 1, c], [r, c + 1]]:
                if 0 <= nr < R and 0 <= nc < C and A[nr][nc] != 3:
                    yield nr, nc
        
        def bfs(queue):
            dist = {node: 0 for node in queue}
            while queue:
                node = queue.popleft()
                for nei in get_neighbors(*node):
                    if nei not in dist:
                        dist[nei] = dist[node] + 1
                        queue.append(nei)
            return dist
        
        fire_queue = deque()
        person_queue = deque()
        
        # Find initial positions of fire and person
        for r, row in enumerate(A):
            for c, v in enumerate(row):
                if v == 1:
                    person_queue.append((r, c))
                elif v == 2:
                    fire_queue.append((r, c))
        
        # Calculate distances
        dist_fire = bfs(fire_queue)
        dist_person = bfs(person_queue)
        
        # Check if person can reach either target cell safely
        for place in ((0, 0), (R - 1, C - 1)):
            if dist_fire.get(place, INF) >= dist_person.get(place, 2 * INF):
                return True
        
        return False

# Test the solution
ob = Solution()
matrix = [
    [0, 0, 0],
    [0, 0, 1],
    [0, 0, 2]
]
print(ob.solve(matrix))
True

How It Works

The algorithm works in three main phases:

  1. Find Initial Positions: Locate the person (1) and fire (2) positions in the matrix

  2. Calculate Distances: Use BFS to find minimum steps needed for fire and person to reach each reachable cell

  3. Check Safety: For both target corners, verify if person arrives before or at the same time as fire

Another Example

# Example with wall blocking the path
matrix2 = [
    [1, 3, 0],
    [0, 3, 0],
    [2, 0, 0]
]

ob = Solution()
print(ob.solve(matrix2))
False

Conclusion

This solution uses BFS to calculate minimum distances for both fire and person, then checks if the person can safely reach either target corner. The key insight is that the person survives if they reach the destination at the same time or before the fire arrives.

Updated on: 2026-03-25T13:59:29+05:30

187 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements