#include "locmin.h"
#include <utility>
#define ll long long
#define INF 10000000000
int n, m, i, j, rezl, rezc;
ll a[501][501], viz[501][501];
ll get_value(int lin, int col){ /// own function for memory saving
    if(lin == 0 || col == 0){
        return INF;
    }
    if(a[lin][col]==0){
        a[lin][col] = value(lin, col);
    }
    return a[lin][col];
}
bool check(int lin, int col){
    ll cur = get_value(lin, col);
    if(lin < 1 || lin > n || col < 1 || col > m){
        return false;
    }
    if((get_value(lin - 1, col) < cur) ||
        (get_value(lin + 1, col) < cur) ||
        (get_value(lin, col - 1) < cur) ||
        (get_value (lin, col + 1) < cur)){
        int nextl = lin, nextc = col;
        if(get_value(lin -1, col) < get_value(lin + 1, col)){
            nextl--;
        }else{
            nextl++;
        }
        if(get_value(nextl, nextc) > get_value(lin, col -1)){
            nextl = lin; nextc = col -1;
        }
        if(get_value(nextl, nextc) > get_value(lin, col + 1)){
            nextl = lin; nextc = col + 1;
        }
        return check(nextl, nextc);
    }
    rezl = lin, rezc = col;
    return true;
}
std::pair <int, int> find_locmin_point(int N, int M) {

    n = N;
    m = M;
    bool santinela = check(1, 1);
    return {rezl, rezc};
}

