File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
src/chapter18divideandconquer Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ import random
2+ import pprint
3+
4+ def peak_find_2d (matrix ):
5+ j = len (matrix [0 ]) // 2
6+
7+ # maxvalue is the global maximum in column j
8+ # rowmax is the row index of the maxvalue
9+ maxvalue , rowmax = - 1 , - 1
10+ for row in range (len (matrix )):
11+ if maxvalue <= matrix [row ][j ]:
12+ maxvalue = matrix [row ][j ]
13+ rowmax = row
14+ print (rowmax , j , maxvalue )
15+
16+ left , right = 0 , 0
17+ if j > 0 :
18+ left = matrix [rowmax ][j - 1 ]
19+ if j < len (matrix [0 ]) - 1 :
20+ right = matrix [rowmax ][j + 1 ]
21+ if left <= maxvalue >= right :
22+ return (rowmax , j , maxvalue )
23+ if left > maxvalue :
24+ half = []
25+ for row in matrix :
26+ half .append (row [:j + 1 ])
27+ return peak_find_2d (half )
28+ if right > maxvalue :
29+ half = []
30+ for row in matrix :
31+ half .append (row [j :])
32+ return peak_find_2d (half )
33+
34+ def generate_2d_array (n = 7 , m = 7 , lower = 0 , upper = 9 ):
35+ return [[random .randint (lower , upper ) for _ in range (m )] for _ in range (n )]
36+
37+ if __name__ == '__main__' :
38+ matrix = generate_2d_array (upper = 9 )
39+ pprint .pprint (matrix )
40+ peak_find_2 (matrix )
You can’t perform that action at this time.
0 commit comments