[英]2D Peak Algorithm fails to find the peak
I just started an MIT course on algorithm, and we were taught the 2D Peak Finding algo.我刚刚开始了麻省理工学院的算法课程,我们学习了 2D 峰值查找算法。 I tried dry running and implementing it yet the algo seems to be failing for this input.
我尝试过空运行并实施它,但算法似乎无法针对此输入。
{5, 0, 3, 2}
{1, 1, 2, 4}
{1, 2, 4, 4}
This is the Algorithm:这是算法:
• Pick middle column j = m/2
• Find global maximum on column j at (i,j)
• Compare(i,j−1),(i,j),(i,j+1)
• Pick left columns of(i,j−1)>(i,j)
• Similarly for right
• (i,j) is a 2D-peak if neither condition holds ← WHY?
• Solve the new problem with half the number of columns.
• When you have a single column, find global maximum and you‘re done.
Update, Here is the code which I tried and doesn't seem to be working:更新,这是我尝试过但似乎不起作用的代码:
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
int findMax(int arr[][MAX], int rows, int mid, int& max)
{
int max_index = 0;
for (int i = 0; i < rows; i++) {
if (max < arr[i][mid]) {
max = arr[i][mid];
max_index = i;
}
}
return max_index;
}
int findPeakRec(int arr[][MAX], int rows, int columns, int mid)
{
int max = 0;
int max_index = findMax(arr, rows, mid, max);
if (mid == 0 || mid == columns - 1)
return max;
if (max >= arr[max_index][mid - 1] && max >= arr[max_index][mid + 1])
return max;
if (max < arr[max_index][mid - 1])
return findPeakRec(arr, rows, columns, mid - ceil((double)mid / 2));
return findPeakRec(arr, rows, columns, mid + ceil((double)mid / 2));
}
int findPeak(int arr[][MAX], int rows, int columns)
{
return findPeakRec(arr, rows, columns, columns / 2);
}
int main()
{
int arr[][MAX] = { { 5, 0, 3, 2 },
{ 1, 1, 2, 4 },
{ 1, 2, 4, 4 },
{ 3, 2, 0, 1 } };
int rows = 4, columns = 4;
cout << findPeak(arr, rows, columns);
return 0;
}
this is how I implemented the algorithm.这就是我实现算法的方式。
The algorithm is correct (Just a spelling mistake in the fourth bullet point: "of" should read "if").算法是正确的(只是第四个要点中的拼写错误:“of”应该读作“if”)。
You missed a correct definition of "peak".您错过了“峰值”的正确定义。 The algorithm for peak finding intends to find a local maximum, not necessarily the global maximum.
寻峰算法旨在寻找局部最大值,而不一定是全局最大值。 For a global maximum the algorithm is trivial, you just look for the maximum value with a row by row scan.
对于全局最大值,算法很简单,您只需逐行扫描查找最大值。
But peak finding can be more efficient as not all values need to be inspected.但峰值查找可能更有效,因为并非所有值都需要检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.