// #include <bits/stdc++.h>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <map>
#include <vector>
#include <iomanip>
#include <string>
#include <queue>
#include <set>
#include <deque>
#include <numeric>
#include <stack>
#include <chrono>
using namespace std;
#define int long long
#define endl '\n'
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define fi first
#define se second
const int N = 4005;
int n, m, dist[N][N];
bool vis[N][N];
string s[N];
vector<int> dx = {0, 0, 1, -1}, dy = {1, -1, 0, 0};
bool check(int x, int y){
return (x > 0 && x <= n && y > 0 && y <= m && !vis[x][y] && s[x][y] != '.');
}
signed bfs(){
deque<pair<int, int>> q;
q.push_back({1, 1});
vis[1][1] = 1;
int ma = 0;
while (q.size()){
auto [x, y] = q.front(); q.pop_front();
ma = max(ma, dist[x][y]);
for (int j = 0; j < 4; j++){
int ddx = dx[j], ddy = dy[j];
int cx = x + ddx, cy = y + ddy;
if (check(cx, cy) && s[cx][cy] == s[x][y]){
dist[cx][cy] = dist[x][y];
q.push_front({cx, cy});
vis[cx][cy] = 1;
}
else if (check(cx, cy)){
dist[cx][cy] = dist[x][y] + 1;
q.push_back({cx, cy});
vis[cx][cy] = 1;
}
}
}
return ma;
}
void solve() {
cin >> n >> m;
for (int i = 1; i <= n; i++){
cin >> s[i];
s[i] = "." + s[i];
}
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++) dist[i][j] = 1e18;
}
dist[1][1] = 1;
cout << bfs() << endl;
return;
}
signed main() {
srand(chrono::steady_clock::now().time_since_epoch().count());
int tc = 1;
// cin >> tc;
while (tc--) solve();
return 0;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |