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

using namespace std;

bool found;
int n,m;
int check;
bool visited[505][505];
int val[505][505];
pair<signed,signed> dapair;

bool inmat(int l, int c)
{
    if (l>0 && l<=n && c>0 && c<=m)
        return 1;
    else
        return 0;
}

void dfs(int l, int c)
{
    if (check>(n*m))
        return;
    if (found || visited[l][c])
        return;
    check++;
    visited[l][c]=1;
    int mi,ls,cs,res;
    mi=1e18+1;
    if (inmat(l-1,c))
    {
        if (!val[l-1][c])
        {
            res=value(l-1,c);
            val[l-1][c]=res;
        }
        res=val[l-1][c];
        if (res<mi)
        {
            mi=res;
            ls=l-1;
            cs=c;
        }
    }
    if (inmat(l+1,c))
    {
        if (!val[l+1][c])
        {
            res=value(l+1,c);
            val[l+1][c]=res;
        }
        res=val[l+1][c];
        if (res<mi)
        {
            mi=res;
            ls=l+1;
            cs=c;
        }
    }
    if (inmat(l,c-1))
    {
        if (!val[l][c-1])
        {
            res=value(l,c-1);
            val[l][c-1]=res;
        }
        res=val[l][c-1];
        if (res<mi)
        {
            mi=res;
            ls=l;
            cs=c-1;
        }
    }
    if (inmat(l,c+1))
    {
        if (!val[l][c+1])
        {
            res=value(l,c+1);
            val[l][c+1]=res;
        }
        res=val[l][c+1];
        if (res<mi)
        {
            mi=res;
            ls=l;
            cs=c+1;
        }
    }
    if (val[l][c]<mi)
    {
        dapair= {l,c};
        found=true;
        return;
    }
    else
    {
        dfs(ls,cs);
    }
}

pair<signed, signed> find_locmin_point(signed N, signed M)
{
    int l,c;
    n=N;
    m=M;
    found=false;
    while(!found)
    {
        check=0;
        l=min(n,max(0LL,(rand()*420)%n+1));
        c=min(m,max(0LL,(rand()*420)%m+1));
        val[l][c]=value(l,c);
        dfs(l,c);
    }
    return dapair;
}
