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

const long long maxn=505;
int table[maxn][maxn];
queue<pair<int,int>> q;

pair <int,int> find_locmin_point(int n, int m) {
    int a=1,b=1;
    bool f=true;
    while(a<=n && b<=m && !q.empty()){
        if(!table[a][b]) table[a][b]=value(a,b);
        f=true;
        if(a>1 && table[a-1][b]<table[a][b]) f=false;

        if(a<n && !table[a+1][b]) table[a+1][b]=value(a+1,b);
        if(a<n && table[a+1][b]<table[a][b]){
            q.push({a+1,b});
            f=false;
        }

        if(b<m && !table[a][b+1]) table[a][b+1]=value(a,b+1);
        if(b<m && table[a][b+1]<table[a][b]){
            q.push({a,b+1});
            f=false;
        }

        if(b>1 && table[a][b-1]<table[a][b]) f=false;

        if(f) return {a,b};
        if(!q.empty()){
            a=q.front().first;
            b=q.front().second;
            q.pop();
        }else{
            if(b+2<=m) q.push({a,b+2});
            else if(a+1<=n){
                q.push({a+1,1});
            }
        }
    }
    return {a,b};
}
