This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define fi first
#define se second
#define pii pair<int, int>
#define pb push_back
#define vi vector<int>
#define all(x) x.begin(), x.end()
using namespace std;
using namespace __gnu_pbds;
using ll = long long int;
using ull = unsigned long long int;
constexpr ll mod = 1e9 + 7;
constexpr ll INF = LONG_LONG_MAX;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
string moves = "URDL";
int main()
{
//tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update> q;
/*freopen("problemname.in", "r", stdin);
freopen("problemname.out", "w", stdout);*/
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n, m;
cin >> n >> m;
char a[n][m];
for(int i = 0;i<n;++i) {
for(int j = 0;j<m;++j) {
cin >> a[i][j];
}
}
bool vis[n][m];
int cc[n][m], c = 0;
memset(cc, 0, sizeof cc);
memset(vis, false, sizeof vis);
for(int i = 0;i<n;++i) {
for(int j = 0;j<m;++j) {
if (!vis[i][j] && a[i][j] != '.') {
queue<pii> q;
q.push({i, j});
++c;
vis[i][j] = true;
cc[i][j] = c;
while(!q.empty()) {
pii node = q.front();
q.pop();
for(int k = 0;k<4;++k) {
int nx = node.fi + dx[k], ny = node.se + dy[k];
if (nx >= 0 && ny >= 0 && nx < n && ny < m) {
if (a[nx][ny] == a[i][j] && !vis[nx][ny]) {
q.push({nx, ny});
vis[nx][ny] = true;
cc[nx][ny] = c;
}
}
}
}
}
}
}
memset(vis, false, sizeof vis);
set<int> adj[c + 1];
int d[c + 1];
for(int i = 0;i<n;++i) {
for(int j = 0;j<m;++j) {
if (!vis[i][j] && a[i][j] != '.') {
queue<pii> q;
q.push({i, j});
vis[i][j] = true;
while(!q.empty()) {
pii node = q.front();
q.pop();
for(int k = 0;k<4;++k) {
int nx = node.fi + dx[k], ny = node.se + dy[k];
if (nx >= 0 && ny >= 0 && nx < n && ny < m) {
if (a[nx][ny] == a[i][j] && !vis[nx][ny]) {
q.push({nx, ny});
vis[nx][ny] = true;
}
if (cc[nx][ny] != cc[i][j] && cc[nx][ny] != 0) {
adj[cc[i][j]].insert(cc[nx][ny]);
adj[cc[nx][ny]].insert(cc[i][j]);
}
}
}
}
}
}
}
queue<int> q;
q.push(cc[0][0]);
bool ok[c + 1];
memset(ok, false, sizeof ok);
ok[cc[0][0]] = true;
d[cc[0][0]] = 0;
int ans = 0;
while(!q.empty()) {
int node = q.front();
q.pop();
for(const int& v:adj[node]) {
if (!ok[v]) {
q.push(v);
ok[v] = true;
d[v] = d[node] + 1;
ans = max(ans, d[v]);
}
}
}
cout << ans + 1 << endl;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |