Skip to content

Commit 08f76ec

Browse files
authored
Merge pull request ephremdeme#150 from Druffl3/dev
Added hourglass Array Datastructure problem solution
2 parents 6fc9d7c + 80da422 commit 08f76ec

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Arrays/maxHourGlass.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# This python3 script accepts a nxn two dimensional matrix
2+
# and calculates the maximum hourglass sum possible from it.
3+
4+
'''
5+
Example:
6+
In this 6x6 Matrix:
7+
8+
1 1 1 0 0 0
9+
0 1 0 0 0 0
10+
1 1 1 0 0 0
11+
0 0 0 1 1 1
12+
0 0 0 0 1 0
13+
0 0 0 1 1 2
14+
15+
The pattern:
16+
1 1 1
17+
0 1 0
18+
1 1 1
19+
20+
makes 1 hour glass. And the sum of this hour glass is:
21+
1 + 1 + 1 + 1 + 1 + 1 + 1 = 7
22+
Similarly we need to find sum of all hourglasses in the Matrix
23+
And print the maximum sum.
24+
'''
25+
26+
#Taking rank of the matrix from user
27+
n = int(input())
28+
l = []
29+
30+
#Converting each string of row values into list and appending it to The
31+
#main two dimensional list 'l'
32+
for i in range(n):
33+
il = list(map(int, input().split()))
34+
l.append(il)
35+
36+
#This will store our expected result
37+
finalSum = 0
38+
39+
#Creating a 3x3 grid index to iterate over the two dimensional list And
40+
#calculate sum of the hourglasses.
41+
#-2 is added to make sure not to index beyond the actual list range.
42+
for r1 in range(n-2):
43+
r2 = r1+1
44+
r3 = r2+1
45+
for c1 in range(n-2):
46+
#to store sum of all hourglasses
47+
res = 0
48+
c2 = c1+1
49+
c3 = c2+1
50+
res = l[r1][c1] + l[r1][c2] + l[r1][c3] + l[r2][c2] + l[r3][c1] + l[r3][c2] + l[r3][c3]
51+
#Maybe the first element is -ve, therefore need to store it no matter what.
52+
if r1 == 0 and c1 == 0:
53+
finalSum = res
54+
#will always store the maximum result
55+
if res > finalSum:
56+
finalSum = res
57+
58+
#print the maximum hourglass sum.
59+
print(finalSum)

0 commit comments

Comments
 (0)