Question: Python Program that reads a matrix MN which represents the map and prints the number of enemies ready to attack the kingdom: # 2 D

Python Program that reads a matrix MN which represents the map and prints the number of enemies ready to attack the kingdom:
#2D array to store map of kingdom
arr=[]
#Take input from user for size of matrix
[M][N]= int(input())
#Taking values from user
for i in range(0,M):
arr.append([int(j) for j in input().split()])
#2D list to store true or false
#True represent current block is already visited
#False represent not visited
check =[]
#initially all values set to false
for i in range(M):
temp =[]
for j in range(N):
temp.append(False)//appends an element to end of the list
check.append(temp)
#variable to store the final sum
sum = int(0)
for i in range(M):
for j in range(N):
if arr[i][j]==0:
if i!=0 and check[i-1][j]== False:
check[i-1][j]= True
sum = sum+arr[i-1][j]
if j!=0 and check[i][j-1]== False:
check[i][j-1]= True
sum = sum+arr[i][j-1]
if j!=N-1 and check[i][j+1]== False:
check[i][j+1]= True
sum = sum+arr[i][j+1]
if i!=M-1 and check[i+1][j]== False:
check[i+1][j]= True
sum = sum+arr[i+1][j]
print(sum)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!