This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//author: Ahmet Alp Orakci
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
char matrix[1005][1005];
int vis[1005 * 1005];
bool viss[1005][1005];
set <int> adj[1005 * 1005];
int comp[1005][1005];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};
#define ONLINE_JUDGE
void solve() {
memset(vis, -1, sizeof(vis));
int r, c;
cin >> r >> c;
for(int i = 1; i <= r; i++) {
for(int j = 1; j <= c; j++) {
cin >> matrix[i][j];
}
}
auto in = [&](int x, int y) -> bool {
return 1 <= x && x <= r && 1 <= y && y <= c;
};
function <void(int, int, int)> dfs = [&](int x, int y, int c) -> void {
if(viss[x][y]) {
return;
}
viss[x][y] = true;
comp[x][y] = c;
for(int i = 0; i < 4; i++) {
int _x = x + dx[i], _y = y + dy[i];
if(in(_x, _y) && matrix[_x][_y] == matrix[x][y]) {
dfs(_x, _y, c);
}
}
};
int cnt = 0;
for(int i = 1; i <= r; i++) {
for(int j = 1; j <= c; j++) {
if(!viss[i][j] && matrix[i][j] != '*') {
dfs(i, j, cnt);
cnt++;
}
}
}
for(int i = 1; i <= r; i++) {
for(int j = 1; j <= c; j++) {
if(i +1 <= r && matrix[i][j] != matrix[i +1][j] && matrix[i][j] != '*' && matrix[i +1][j] != '*') {
adj[comp[i][j]].emplace(comp[i +1][j]);
}
if(j +1 <= c && matrix[i][j] != matrix[i][j +1] && matrix[i][j] != '*' && matrix[i][j +1] != '*') {
adj[comp[i][j]].emplace(comp[i][j +1]);
}
if(i -1 >= 1 && matrix[i][j] != matrix[i -1][j] && matrix[i][j] != '*' && matrix[i -1][j] != '*') {
adj[comp[i][j]].emplace(comp[i -1][j]);
}
if(j -1 >= 1 && matrix[i][j] != matrix[i][j -1] && matrix[i][j] != '*' && matrix[i][j -1] != '*') {
adj[comp[i][j]].emplace(comp[i][j -1]);
}
}
}
priority_queue <pair <int, int>, vector <pair <int, int>>, greater <>> q;
q.emplace(1, 0);
while(!q.empty()) {
auto [d, x] = q.top();
q.pop();
if(vis[x] != -1) {
continue;
}
cerr << x << " " << d << "\n";
vis[x] = d;
for(const int child : adj[x]) {
if(vis[child] == -1) {
q.emplace(d +1, child);
}
}
}
cout << *max_element(vis, vis + 1005 * 1005);
return;
}
signed main() {
#ifndef ONLINE_JUDGE
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int t = 1; //cin >> t;
for(int i = 1; i <= t; i++) {
solve();
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |