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 task "C"
#define ll long long
#define ld long double
#define fi first
#define se second
#define pb push_back
using namespace std;
const int MAXN = 1e3 + 5;
const ll INF = 1e18 + 5;
int m, n;
string s[MAXN];
void Input()
{
cin >> m >> n;
for (int i = 1; i <= m; i++)
{
cin >> s[i];
s[i] = ',' + s[i];
}
}
int lft[MAXN][MAXN], up[MAXN][MAXN], down[MAXN][MAXN], rght[MAXN][MAXN];
int d[MAXN][MAXN];
struct TState
{
int x, y;
bool Valid() const
{
return x > 0 && x <= m && y > 0 && y <= n;
}
};
int Ox[4] = {1, -1, 0, 0};
int Oy[4] = {0, 0, 1, -1};
void Solve()
{
pair<int, int> S, C;
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (s[i][j] == '#')
{
lft[i][j] = 0;
up[i][j] = 0;
} else
{
if (s[i][j] == 'S')
S = {i, j};
if (s[i][j] == 'C')
C = {i, j};
up[i][j] = up[i - 1][j] + 1;
lft[i][j] = lft[i][j - 1] + 1;
}
}
}
for (int i = m; i >= 1; i--)
{
for (int j = n; j >= 1; j--)
{
if (s[i][j] == '#')
{
rght[i][j] = 0;
down[i][j] = 0;
} else
{
rght[i][j] = rght[i][j + 1] + 1;
down[i][j] = down[i + 1][j] + 1;
}
}
}
deque<TState> Q;
memset(d, -1, sizeof(d));
Q.pb({S.fi, S.se});
d[S.fi][S.se] = 0;
while (!Q.empty())
{
auto u = Q.front();
Q.pop_front();
if (u.x == C.fi && u.y == C.se)
{
cout << d[u.x][u.y];
return;
}
TState v = {u.x, u.y - lft[u.x][u.y] + 1};
if (v.Valid() && d[v.x][v.y] == -1)
{
d[v.x][v.y] = d[u.x][u.y] + 1;
Q.pb(v);
}
v = {u.x, u.y + rght[u.x][u.y] - 1};
if (v.Valid() && d[v.x][v.y] == -1)
{
d[v.x][v.y] = d[u.x][u.y] + 1;
Q.pb(v);
}
v = {u.x - up[u.x][u.y] + 1, u.y};
if (v.Valid() && d[v.x][v.y] == -1)
{
d[v.x][v.y] = d[u.x][u.y] + 1;
Q.pb(v);
}
v = {u.x + down[u.x][u.y] - 1, u.y};
if (v.Valid() && d[v.x][v.y] == -1)
{
d[v.x][v.y] = d[u.x][u.y] + 1;
Q.pb(v);
}
for (int c = 0; c < 4; c++)
{
TState v = {u.x + Ox[c], u.y + Oy[c]};
if (v.Valid() && d[v.x][v.y] == -1)
{
d[v.x][v.y] = d[u.x][u.y] + 1;
Q.pb(v);
}
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
if (fopen(task".INP","r"))
{
freopen(task".INP","r",stdin);
//freopen(task".OUT","w",stdout);
}
Input();
Solve();
}
Compilation message (stderr)
portals.cpp: In function 'int main()':
portals.cpp:133:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
133 | freopen(task".INP","r",stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |