Check if all enemies are killed with bombs placed in a matrix in Python

Suppose we have a matrix mat. There are few different values as follows The cells of matrix can hold any of these 3 characters

• 0 for empty area.
• 1 for bomb.
• 2 for Enemies.

Now bomb can blast in only horizontal and vertical directions from one end to another. We have to check whether all enemies will die when bomb explodes or not.

So, if the input is like

 0 0 2 0 0 1 0 0 0 2 0 0 0 0 1 0

then the output will be True, because bomb at place [1, 1] can fill enemy at place [2, 1] and enemy at [0, 2] will be killed by bomb placed at [3, 2].

To solve this, we will follow these steps −

• r := row count of mat
• c := col count of mat
• i := 0, j := 0, x := 0, y := 0
• for i in range 0 to r - 1, do
• for j in range 0 to c - 1, do
• if mat[i, j] is 1, then
• for x in range 0 to r - 1, do
• if mat[x, j] is not 1, then
• mat[x, j] := 0
• for y in range 0 to c - 1, do
• if mat[i, y] is not 1, then
• mat[i, y] := 0
• for i in range 0 to r - 1, do
• for j in range 0 to c - 1, do
• if mat[i, j] is 2, then
• return False
• return True

Let us see the following implementation to get better understanding −

Example

Live Demo

def solve(mat):
r = len(mat)
c = len(mat[0])
i, j, x, y = 0, 0, 0, 0
for i in range(r):
for j in range(c):
if mat[i][j] == 1:
for x in range(r):
if mat[x][j] != 1:
mat[x][j] = 0
for y in range(c):
if mat[i][y] != 1:
mat[i][y] = 0
for i in range(r):
for j in range(c):
if mat[i][j] == 2:
return False
return True
matrix = [ [0,0,2,0], [0,1,0,0], [0,2,0,0], [0,0,1,0] ]
print(solve(matrix))

Input

[
[0,0,2,0],
[0,1,0,0],
[0,2,0,0],
[0,0,1,0]
]

Output

True