![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- if mat[x, j] is not 1, then
- for y in range 0 to c - 1, do
- if mat[i, y] is not 1, then
- mat[i, y] := 0
- if mat[i, y] is not 1, then
- for x in range 0 to r - 1, do
- if mat[i, j] is 1, then
- for j in range 0 to c - 1, do
- 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
- if mat[i, j] is 2, then
- for j in range 0 to c - 1, do
- return True
Let us see the following implementation to get better understanding −
Example
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
Advertisements