Suppose we have a 2d binary matrix, where 1 represents a bomb and 0 represents an empty cell. When a bomb explodes, all the spaces along on the same row and column are damaged. We have to find the number of spaces we can stand in to not get damaged.
So, if the input is like
1 | 1 | 0 |
0 | 0 | 0 |
0 | 0 | 0 |
then the output will be 2, as there are two spaces the bottom right cell and the middle right cell are safe.
To solve this, we will follow these steps:
r := a list of size same as row count of matrix and fill with false
c := a list of size same as column count of matrix and fill with false
for i in range 0 to row count of matrix - 1, do
for j in range 0 to column count of matrix - 1, do
if matrix[i, j] is same as 1, then
r[i] := True, c[j] := True
ct := 0
for i in range 0 to row count of matrix - 1, do
for j in range 0 to column count of matrix - 1, do
if r[i] is False and c[j] is False, then
ct := ct + 1
return ct
Let us see the following implementation to get better understanding:
Example
class Solution: def solve(self, matrix): r = [False for i in range(len(matrix))] c = [False for i in range(len(matrix[0]))] for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 1: r[i] = True c[j] = True ct = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if r[i] == False and c[j] == False: ct += 1 return ct ob = Solution() matrix = [ [1, 1, 0], [0, 0, 0], [0, 0, 0] ] print(ob.solve(matrix))
Input
[ [1, 1, 0], [0, 0, 0], [0, 0, 0] ]
Output
2