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>
#define pi pair<int, int>
using namespace std;
const int MAXN = 4005, INF = 1e9 + 1;
string grid[MAXN];
int dist[MAXN][MAXN];
bool visited[MAXN][MAXN];
// queue<pi> q;
deque<pi> q;
int n, m, ans = 0;
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
cin >> grid[i];
// for (int i = 0; i < n; i++)
// {
// for (int j = 0; j < m; j++)
// cout << grid[i][j];
// cout << endl;
// }
// cout << endl;
dist[0][0] = 1;
// q.push({0, 0});
q.push_back({0, 0});
while (!q.empty())
{
// for (int i = 0; i < n; i++)
// {
// for (int j = 0; j < m; j++)
// cout << dist[i][j] << " ";
// cout << endl;
// }
// cout << endl;
// int i = q.front().first, j = q.front().second;
int i = q.front().first, j = q.front().second;
q.pop_front();
visited[i][j] = true;
ans = max(ans, dist[i][j]);
if (i + 1 < n && !visited[i + 1][j]) // 1
{
if (grid[i + 1][j] == '.')
{
}
else if (grid[i][j] == grid[i + 1][j])
{
dist[i + 1][j] = min((dist[i + 1][j] == 0 ? INF : dist[i + 1][j]), dist[i][j]);
q.push_front({i + 1, j});
}
else if (grid[i][j] != grid[i + 1][j])
{
dist[i + 1][j] = min((dist[i + 1][j] == 0 ? INF : dist[i + 1][j]), dist[i][j] + 1);
q.push_back({i + 1, j});
}
}
if (j + 1 < m && !visited[i][j + 1]) // 2
{
if (grid[i][j + 1] == '.')
{
}
else if (grid[i][j] == grid[i][j + 1])
{
dist[i][j + 1] = min((dist[i][j + 1] == 0 ? INF : dist[i][j + 1]), dist[i][j]);
q.push_front({i, j + 1});
}
else if (grid[i][j] != grid[i][j + 1])
{
dist[i][j + 1] = min((dist[i][j + 1] == 0 ? INF : dist[i][j + 1]), dist[i][j] + 1);
q.push_back({i, j + 1});
}
}
if (i - 1 >= 0 && !visited[i - 1][j]) // 3
{
if (grid[i - 1][j] == '.')
{
}
else if (grid[i][j] == grid[i - 1][j])
{
dist[i - 1][j] = min((dist[i - 1][j] == 0 ? INF : dist[i - 1][j]), dist[i][j]);
q.push_front({i - 1, j});
}
else if (grid[i][j] != grid[i - 1][j])
{
dist[i - 1][j] = min((dist[i - 1][j] == 0 ? INF : dist[i - 1][j]), dist[i][j] + 1);
q.push_back({i - 1, j});
}
}
if (j - 1 >= 0 && !visited[i][j - 1]) // 4
{
if (grid[i][j - 1] == '.')
{
}
else if (grid[i][j] == grid[i][j - 1])
{
dist[i][j - 1] = min((dist[i][j - 1] == 0 ? INF : dist[i][j - 1]), dist[i][j]);
q.push_front({i, j - 1});
}
else if (grid[i][j] != grid[i][j - 1])
{
dist[i][j - 1] = min((dist[i][j - 1] == 0 ? INF : dist[i][j - 1]), dist[i][j] + 1);
q.push_back({i, j - 1});
}
}
}
cout << ans << endl;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |