Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 03adefc

Browse files
authoredOct 15, 2024··
Add files via upload
1 parent eeeb9ab commit 03adefc

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
 

‎searches/Peak_Element_on_2D.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
def find_peak_util(matrix, left, right, row_count):
2+
mid_col = (left + right) // 2
3+
4+
max_row_index = 0
5+
for i in range(row_count):
6+
if matrix[i][mid_col] > matrix[max_row_index][mid_col]:
7+
max_row_index = i
8+
9+
10+
if (mid_col == 0 or matrix[max_row_index][mid_col] >= matrix[max_row_index][mid_col - 1]) and \
11+
(mid_col == len(matrix[0]) - 1 or matrix[max_row_index][mid_col] >= matrix[max_row_index][mid_col + 1]):
12+
return matrix[max_row_index][mid_col]
13+
14+
15+
if mid_col > 0 and matrix[max_row_index][mid_col - 1] > matrix[max_row_index][mid_col]:
16+
return find_peak_util(matrix, left, mid_col - 1, row_count)
17+
18+
return find_peak_util(matrix, mid_col + 1, right, row_count)
19+
20+
def find_peak(matrix):
21+
if not matrix or not matrix[0]:
22+
return None
23+
return find_peak_util(matrix, 0, len(matrix[0]) - 1, len(matrix))
24+
25+
matrix = [
26+
[10, 8, 10, 10],
27+
[14, 13, 12, 11],
28+
[15, 9, 11, 21],
29+
[16, 17, 19, 20]
30+
]
31+
32+
peak = find_peak(matrix)
33+
print(f"Peak element is: {peak}")

0 commit comments

Comments
 (0)
Please sign in to comment.