48 lines
1.7 KiB
Markdown
48 lines
1.7 KiB
Markdown
A peak in a 2D list of values is a value that is not smaller than its 4 neighbours. Assume all values are natural numbers.
|
|
|
|
For example, consider the following list of values
|
|
a = [[10, 8, 10, 10],
|
|
[14, 13, 12, 11],
|
|
[15, 9, 11, 21],
|
|
[16, 17, 19, 20]]
|
|
|
|
Here, 21 is the only peak.
|
|
|
|
Write a python program that uses recursion to find a peak (not all, just one peak) given a list of 2D values (m columns, n rows).
|
|
Your function should return the list index as a tuple of the peak.
|
|
To do so you must implement the following recursive algorithm that uses the same idea as binary search (i.e., divide and conquer).
|
|
• Pick middle column j = m//2
|
|
• Find global max on column j at (i, j), if there are multiple global max, pick the smallest possible i
|
|
• Compare (i, j-1), (i, j), (i, j+1)
|
|
• Pick left columns if (i, j-1) > (i, j)
|
|
◦ Similar for right
|
|
• (i, j) is a 2D-peak if neither conditions holds
|
|
• Solve the new problem with half the number of columns
|
|
• When you have a single column, find global max and you are done (again, if there are multiple global max, pick the smallest possible index)
|
|
|
|
Similar to Q4, this method will always find a specific peak among all the others that may exist in the list of 2D values. Your program must follow this behaviour.
|
|
|
|
Input specification:
|
|
• n lines and m columns of numbers separated by space
|
|
• follow by an empty line input to determine the end of the input
|
|
|
|
Output specification:
|
|
• The index as a tuple of the peak
|
|
|
|
Sample testcases (The bolded text are user input, including the blank line)
|
|
|
|
Case 1:
|
|
10 8 10 10
|
|
14 13 12 11
|
|
15 9 11 21
|
|
16 17 19 20
|
|
|
|
(2, 3)
|
|
|
|
Case 2:
|
|
1 2 3
|
|
4 5 6
|
|
7 8 9
|
|
10 11 12
|
|
|
|
(3, 2) |