Submatrix Sum – Integers Start with D: The program must accept an integer matrix of size R*C and two integers K, D as the input. D represents a non-zero digit. The program must print the sum of all the integers present in the first occurring K*K submatrix where each integer starts with the digit D. If there is no such submatrix, the program must print -1 as the output.
Boundary Condition(s):
2 <= R, C <= 50
1 <= Matrix element value <= 1000
2 <= K <= Minimum value between R and C
1 <= D <= 9
Input Format:
The first line contains R and C separated by a space.
The next R lines, each contains C integer values separated by a space.
The (R+2)nd line contains K and D separated by a space.
Output Format:
The first line contains the sum or -1 as per the given condition.
Example Input/Output 1:
Input:
4 5
12 57 23 22 61
64 45 52 51 19
25 55 55 53 40
45 65 84 68 81
2 5
Output:
211
Explanation:
Here K = 2 and D = 5.
The only 2*2 submatrix where each integer starts with 5 is given below.
52 51
55 53
The sum of integers in the above 2*2 submatrix is 211, which is printed as the output.
Example Input/Output 2:
Input:
6 5
66 44 13 12 63
83 96 41 23 11
10 24 29 25 95
27 28 26 26 81
22 21 22 26 19
28 27 27 93 53
3 2
Output:
227
Example Input/Output 3:
Input:
4 7
82 87 81 76 87 95 86
62 89 48 86 44 94 88
80 71 12 77 88 84 18
89 84 85 57 85 27 93
4 8
Output:
-1
a,b=map(int,input().split())
l=[[v for v in input().split()]for i in range(a)]
k,d=map(int,input().split())
for i in range(0,a-k+1):
for j in range(0,b-k+1):
r=[]
for t in range(i,i+k):
q=[];y=0
for u in range(j,j+k):
if int(l[t][u][0])==d:q.append(int(l[t][u]))
else:y=1
r.append(q)
if y==1:break
if y==0:
for i in r:y+=sum(i)
print(y);quit()
print(-1)