#include "locmin.h"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

vector<vector<ll>> mem;

ll val(int i, int j) {
    // cout << i << " " << j << "\n";
    if (i < 0 || i >= mem.size() || j < 0 || j >= mem[0].size()) {
        return 1000000000000000001;
    }
    if (mem[i][j] != -1) {
        return mem[i][j];
    }
    return mem[i][j] = value(i + 1, j + 1);
}

bool check_point(int i, int j) {
    cout << i << " " << j << "\n";
    vector<pair<int, int>> cs = {{i - 1, j}, {i, j - 1}, {i + 1, j}, {i, j + 1}};
    for (auto [i2, j2] : cs) {
        if (i2 < 0 || i2 >= mem.size() || j2 < 0 || j2 >= mem[0].size()) {
            continue;
        }
        if (mem[i2][j2] != -1 && val(i2, j2) < val(i, j)) {
            return false;
        }
    }
    for (auto [i2, j2] : cs) {
        if (val(i2, j2) < val(i, j)) {
            return false;
        }
    }
    return true;
}

pair<int, int> find_locmin_point(int n, int m) {
    mem.assign(n, vector<ll>(m, -1));
    int i = 0;
    while (true) {
        int mnJ = 0;
        for (int j = 0; j < m; ++j) {
            if (check_point(i, j)) return {i + 1, j + 1};
            if (val(i, j) < val(i, mnJ)) {
                j = mnJ;
            }
        }
        int mnI = 0;
        for (int ii = 0; ii < n; ++ii) {
            if (check_point(ii, mnJ)) return {ii + 1, mnJ + 1};
            if (val(ii, mnJ) < val(mnI, mnJ)) {
                mnI = ii;
            }
        }
    }
}
