-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperimeter_of_a_shape.m
105 lines (90 loc) · 1.9 KB
/
perimeter_of_a_shape.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
% # Python3 program to find perimeter of area
% # covered by 1 in 2D matrix consists of 0's and 1's.
% https://www.geeksforgeeks.org/find-perimeter-shapes-formed-1s-binary-matrix/
%
% R = 3
% C = 5
%
% # Find the number of covered side for mat[i][j].
% def numofneighbour(mat, i, j):
%
% count = 0;
%
% # UP
% if (i > 0 and mat[i - 1][j]):
% count+= 1;
%
% # LEFT
% if (j > 0 and mat[i][j - 1]):
% count+= 1;
%
% # DOWN
% if (i < R-1 and mat[i + 1][j]):
% count+= 1
%
% # RIGHT
% if (j < C-1 and mat[i][j + 1]):
% count+= 1;
%
% return count;
%
% # Returns sum of perimeter of shapes formed with 1s
% def findperimeter(mat):
%
% perimeter = 0;
%
% # Traversing the matrix and finding ones to
% # calculate their contribution.
% for i in range(0, R):
% for j in range(0, C):
% if (mat[i][j]):
% perimeter += (4 - numofneighbour(mat, i, j));
%
% return perimeter;
%
% # Driver Code
% mat = [ [0, 1, 0, 0, 0],
% [1, 1, 1, 0, 0],
% [1, 0, 0, 0, 0] ]
%
% print(findperimeter(mat), end="\n");
%
% # This code is contributed by Akanksha Rai
R = 3;
C = 5;
mat = [0, 1, 0, 0, 0;
1, 1, 1, 0, 0;
1, 0, 0, 0, 0];
find_perimeter(mat,R,C)
function count = num_of_neighbour(mat, i, j)
% Find the number of covered side for mat(i,j)
count = 0;
[R, C] = size(mat);
% Up
if i > 1 && mat(i-1,j) == 1
count = count + 1;
end
% Left
if j > 1 && mat(i,j-1)
count = count + 1;
end
% Down
if i < R-1 && mat(i+1,j)
count = count + 1;
end
% Right
if j < C-1 && mat(i, j+1)
count = count + 1;
end
end
function perimeter = find_perimeter(mat,R,C)
% Returns the sum of perimeter of shapes formed with 1s
perimeter = 0;
for i = 1:R
for j = 1:C
if mat(i,j)
perimeter = perimeter + (4 - num_of_neighbour(mat, i, j));
end
end
end
end