Formal Problem Statement - Find a peak in a 2D array, where a is a 2D-peak iff a ≥ b, a ≥ d, a ≥ c, a ≥ e. If there are more than one peaks, just return one of them.
Greedy Ascent Algorithm works on the principle, that it selects a particular element to start with. Then it begins traversing across the array, by selecting the neighbour with higher value. If there is no neighbour with a higher value than the current element, it just returns the current element.
Logically, this algorithm is correct, as it returns the element - which has none of it's neighbours greater than the current element.
After a bit of thought, we can come to the conclusion that, in a worst case, the whole array will be transversed. Hence, its time complexity is Θ(mn).
Finally, the code using recursion would be,
#include <iostream> using namespace std; int a[100][100], n, m; int recur(int i, int j) { if (i > 0 && a[i - 1][j] > a[i][j]) return recur(i - 1, j); else if (i < n - 1 && a[i + 1][j] > a[i][j]) return recur(i + 1, j); else if (j > 0 && a[i][j - 1] > a[i][j]) return recur(i, j - 1); else if (j < n - 1 && a[i][j + 1] > a[i][j]) return recur(i, j + 1); else return a[i][j]; } int main() { cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> a[i][j]; } } cout << recur(0, 0); return 0; }
Can you please explain it's complexity calculation which is O(mn)
ReplyDeleteT(n,m) = T(n, m/2) + O(n)
DeleteT(n,1) = O(n)
T(n,m) = O(n) + ........+ O(n) = log base 2 n
T(n,m) = O(log base 2 n)
No its nlog base 2 m
Deletebecause O(n) is added log base 2 of m times since m is being m / 2 in each recursion.
your code snippet is very easy. Thank you for making me understand the concept.
ReplyDeleteoracle training in bangalore
Perhaps your 4th condition -- else if (j < n - 1 && a[i][j + 1] > a[i][j]) return recur(i, j + 1); is wrong. It should have m instead as n because you are taking the number of columns by m.
ReplyDeleteIt should be something like -- else if (j < m - 1 && a[i][j + 1] > a[i][j]) return recur(i, j + 1);
Try you code with following input:
2 3
1 2 3
4 5 6
Thanks for sharing the information though...!
instagram takipçi satın al
ReplyDeleteinstagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
beykoz mitsubishi klima servisi
ReplyDeletependik vestel klima servisi
kadıköy samsung klima servisi
maltepe mitsubishi klima servisi
kadıköy mitsubishi klima servisi
üsküdar mitsubishi klima servisi
maltepe daikin klima servisi
kartal toshiba klima servisi
ümraniye toshiba klima servisi