#include "locmin.h"
#include <bits/stdc++.h>
#pragma once
using namespace std;
bool a[502][502];
int n, m;
pair<int, int> cand = {1, 1};
bool in(pair<int, int> coord) {
    return coord.first >= 1 && coord.first <= n && coord.second >= 1 && coord.second <= m;
}
pair<int, int> diris[4] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
bool oka[502][502];
int cnt = 0;
std::pair <int, int> find_locmin_point(int N, int M) {
    n = N;
    m = M;

    while(1) {
        bool ok = 1;
        pair<int, int> newcandf;

        if(a[cand.first][cand.second] == 0) {
            int val = value(cand.first, cand.second);
            cnt++;
            a[cand.first][cand.second] = val;
        }

        for(int i = 0; i < 4; i++) {
            pair<int, int> newcand;
            newcand.first = cand.first + diris[i].first;
            newcand.second = cand.second + diris[i].second;

            if(in(newcand)) {
                if(a[newcand.first][newcand.second] == 0) {
                    int val = value(newcand.first, newcand.second);
                    cnt++;
                    a[newcand.first][newcand.second] = val;
                }

                if(a[newcand.first][newcand.second] <= a[cand.first][cand.second]) {
                    oka[cand.first][cand.second] = 1;
                    newcandf = newcand;
                    ok = 0;
                    break;
                }
            }
        }

        if(n == 1 && cnt > 30 || n > 1 && cnt > 2026)
            break;

        if(ok)
            return cand;
        else {
            cand = newcandf;
        }
    }

    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++)
            if(oka[i][j] == 0)
                return {i, j};
}
