#include "locmin.h"
#include <bits/stdc++.h>

using namespace std;

static int drow[]={ -1, -0, +0, +1 };
static int dcol[]={ -0, -1, +1, +0 };

map<pair<int, int>, int> mp;

int query(int x, int y) {
    if (!mp.count({x, y})) {
        mp[{x, y}] = value(x, y);
    }
    return mp[{x, y}];
}

pair <int, int> find_locmin_point(int N, int M) {
    long long val = query(1, 1);
    int ptrx = 1, ptry = 1;

    int t = N * M;
    while (t--) {
        vector<array<int, 3>> in;

        auto add = [&](int x, int y) {
            if (x < 1 || x > N || y < 1 || y > M) {
                return;
            }

            int v = query(x, y);
            if (v >= val) {
                return;
            }

            in.push_back({v, x, y});
        };

        for (int i = 0; i < 4; ++i) {
            add(ptrx + drow[i], ptry + dcol[i]);
        }

        sort(in.begin(), in.end());

        if (in.empty()) {
            return {ptrx, ptry};
        }

        val = in[0][0];
        ptrx = in[0][1], ptry = in[0][2];
    }

    return {ptrx, ptry};
}
