#include <bits/stdc++.h>
#define MAXN 500
#define fi first
#define se second
#include "locmin.h"
using namespace std;
long long val[MAXN+5][MAXN+5], vis[MAXN+5][MAXN+5];
stack<pair<int, int>>q;
pair<int, int> dfs(int r, int c, int n, int m) {
    int nr=0, nrvec=0;
    vis[r][c]=1;
    if (r>1) {
        if (val[r-1][c]==0) val[r-1][c]=value(r-1, c);
        if (val[r][c]>val[r-1][c] && vis[r-1][c]==0)  q.push({r-1, c});
        else nr++;
        vis[r-1][c]=1;
        nrvec++;
    }
    if (r<n) {
        if (val[r+1][c]==0) val[r+1][c]=value(r+1, c);
        if (val[r][c]>val[r+1][c] && vis[r+1][c]==0) q.push({r+1, c});
        else nr++;
        vis[r+1][c]=1;
        nrvec++;
    }
    if (c>1) {
        if (val[r][c-1]==0) val[r][c-1]=value(r, c-1);
        if (val[r][c]>val[r][c-1] && vis[r][c-1]==0) q.push({r, c-1});
        else nr++;
        vis[r][c-1]=1;
        nrvec++;
    }
    if (c<m) {
        if (val[r][c+1]==0) val[r][c+1]=value(r, c+1);
        if (val[r][c]>val[r][c+1] && vis[r][c+1]==0) q.push({r, c+1});
        else nr++;
        vis[r][c+1]=1;
        nrvec++;
    }
    if (nr==nrvec) return make_pair(r, c);
    auto x=q.top();
    q.pop();
    r=x.fi;
    c=x.se;
    q.pop();
    return dfs(r, c, n, m);
}

pair<int, int> find_locmin_point(int N, int M) {
    int r=(N+1)/2;
    int c=(M+1)/2;
    val[r][c]=value(r, c);
    return dfs(r, c, N , M);
}
