You are given an m*n matrix.write a program to compute the perimeter of the matrix and print the result.Perimeter of a matrix is defined as the sum of all elements of the four edges of the matrix.
Input
The first line of input containing the positive integer.
The second line of input containing the positive integer.
The next N lines of input space-separated integers.
Explanation
The input should be
3
4
1 2 3 4
5 6 7 8
9 10 11 12
The output should be 1+2+3+4+8+12+11+10+9+5 = 65
Sample Input1
3
4
1 2 3 4
5 6 7 8
9 10 11 12
Sample Output1
65
def ReadMatrix():
m = int(input())
n = int(input())
M = []
for _ in range(m):
line = input()
M.append([int(s) for s in line.split()])
return M
def CalcPerimetr(M):
p = sum(M[0]) + sum(M[-1])
for i in range(1, len(M)-1):
p += M[i][0] + M[i][-1]
return p
M = ReadMatrix()
p = CalcPerimetr(M)
print(p)
Comments
Leave a comment