#include <bits/stdc++.h>
#ifdef ULVI
#define db(x) cerr<<"[ "<<#x<<" = "<<(x)<<" ]\n"
#define dbv(v) cerr<<#v<<" = [ ";for(auto &__x : v)cerr<<__x<<' ';cerr<<"]\n"
#define line() cerr<<string(80, '-')<<'\n'
#else
#define db(x)
#define dbv(v)
#define line()
#endif
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define ff first
#define ss second
#define enld endl
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair<ll,ll> pll;
const ll sz=2e5+100;
const ll mod=1e9+7;
const ll inf=1e18;
template<class T>
using indexed_set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll xx[]={1,-1,0,0};
ll yy[]={0,0,1,-1};
void solve(){
ll n,m;
cin>>n>>m;
vector<string> v(n+5);
for(ll i=1;i<=n;i++){
cin>>v[i];
v[i]='&'+v[i];
}
vector<vector<ll>> dist(n+5,vector<ll>(m+5,inf));
dist[1][1]=1;
deque<pll> dq;
dq.push_back({1,1});
while(!dq.empty()){
auto [x,y]=dq.front();
dq.pop_front();
for(ll i=0;i<4;i++){
ll nx=x+xx[i],ny=y+yy[i];
if(nx<1 || ny<1 || nx>n || ny>m) continue;
if(v[nx][ny]=='.') continue;
ll c=(v[x][y]!=v[nx][ny]);
if(dist[nx][ny]>dist[x][y]+c){
dist[nx][ny]=dist[x][y]+c;
if(c) dq.push_back({nx,ny});
else dq.push_front({nx,ny});
}
}
}
ll mx=0;
for(ll i=1;i<=n;i++){
for(ll j=1;j<=m;j++){
if(v[i][j]=='.') continue;
mx=max(mx,dist[i][j]);
}
}
cout<<mx<<'\n';
}
int main(){
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
ios_base::sync_with_stdio(0);
cin.tie(0);
ll t=1;
//cin>>t;
for(ll _=1;_<=t;_++){
//cout<<"Scenario #"<<_<<":\n";
solve();
}
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |