#include <numeric>
#include <vector>
#include <queue>
#include <stdlib.h>
#include "locmin.h"

std::pair<int, int> find_locmin_point(int N, int M) {
    std::vector<long long> values(N * M, 0);
    const auto v = [N, M, &values] (int r, int c) {
        if (r < 0 || c < 0 || r >= N || c >= M) exit(-1);
        if (!values[r * M + c]) values[r * M + c] = value(r + 1, c + 1);
        return values[r * M + c];
    };

    int r = 0, c = 0;
    while (true) {
        long long n = r <= 0 ? 1e18+1 : v(r - 1, c);
        long long w = c <= 0 ? 1e18+1 : v(r, c - 1);
        long long s = r >= N ? 1e18+1 : v(r + 1, c);
        long long e = c >= M ? 1e18+1 : v(r, c + 1);
        long long x = v(r, c);
        long long t = std::min(std::min(std::min(n, e), std::min(s, w)), x);
        if (t == n) r--;
        else if (t == w) c--;
        else if (t == s) r++;
        else if (t == e) c++;
        else return  { r + 1, c + 1 };
    }
}
