Program to find number of places are safe when bomb explodes in Python?

Suppose we have a 2D binary matrix where 1 represents a bomb and 0 represents an empty cell. When a bomb explodes, all spaces along the same row and column are damaged. We need to find the number of safe positions where we can stand without getting damaged.

So, if the input is like ?

1 1 0
0 0 0
0 0 0

Then the output will be 2, as the bottom-right cell (2,2) and the middle-right cell (1,2) are safe positions.

Approach

To solve this problem, we follow these steps ?

  • Create boolean arrays to track which rows and columns contain bombs
  • Mark all rows and columns that have at least one bomb
  • Count cells that are in unmarked rows AND unmarked columns

Example

class Solution:
    def solve(self, matrix):
        rows = len(matrix)
        cols = len(matrix[0])
        
        # Track which rows and columns have bombs
        bomb_rows = [False] * rows
        bomb_cols = [False] * cols
        
        # Mark rows and columns containing bombs
        for i in range(rows):
            for j in range(cols):
                if matrix[i][j] == 1:
                    bomb_rows[i] = True
                    bomb_cols[j] = True
        
        # Count safe positions
        safe_count = 0
        for i in range(rows):
            for j in range(cols):
                # Safe if neither row nor column has a bomb
                if not bomb_rows[i] and not bomb_cols[j]:
                    safe_count += 1
        
        return safe_count

# Test the solution
solution = Solution()
matrix = [
    [1, 1, 0],
    [0, 0, 0],
    [0, 0, 0]
]

result = solution.solve(matrix)
print(f"Number of safe positions: {result}")
Number of safe positions: 2

How It Works

Let's visualize the bomb explosion pattern ?

Original Matrix B B After Explosion S S

In this example, bombs at positions (0,0) and (0,1) damage the entire first row and first two columns. Only positions (1,2) and (2,2) remain safe.

Time and Space Complexity

  • Time Complexity: O(m × n) where m and n are matrix dimensions
  • Space Complexity: O(m + n) for the boolean arrays

Conclusion

This algorithm efficiently finds safe positions by tracking which rows and columns contain bombs. A cell is safe only if both its row and column are bomb-free.

Updated on: 2026-03-25T12:08:00+05:30

226 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements