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>
typedef long long ll;
using namespace std;
char matrix[404][404];
int visited[404][404];
int dp[404][404], dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, 1, -1}, n, m;
bool valid(int x, int y){
return ((1<=x && x<=n) && (1<=y && y<=m));
}
int cnt;
bool dfs(int x, int y, int c){
if (visited[x][y]) return visited[x][y]==1e9;
visited[x][y] = c+1;
cnt++;
bool ret = 1;
int nx1 = x+dx[c], nx2 = y+dy[c];
if (valid(nx1, nx2)){
ret &= dfs(nx1, nx2, c);
}
int d = 2;
if (!c && matrix[x][y]=='Z') d = 3;
if (c && matrix[x][y]=='N') d = 3;
int nx3 = x+dx[d], nx4 = y+dy[d];
if (valid(nx3, nx4)){
if (d==2 && matrix[nx3][nx4]=='N') ret &= dfs(nx3, nx4, 0);
else if (d==3 && matrix[nx3][nx4]=='Z') ret &= dfs(nx3, nx4, 0);
else ret &= dfs(nx3, nx4, 1);
}
visited[x][y] = 1e9;
return ret;
}
int main(){
scanf("%d %d", &n, &m);
for (int i=1;i<=n;i++){
scanf("%s", matrix[i]+1);
for (int j=1;j<=m;j++) dp[i][j] = 1e9;
}
for (int i=1;i<=n;i++){
for (int i=1;i<=n;i++) fill(visited[i]+1, visited[i]+m+1, 0);
cnt = 0;
for (int j=1;j<=m;j++){
cnt++;
visited[i][j] = 1;
if (matrix[i][j]=='N'){
if (i+1<=n && !dfs(i+1, j, 1)) break;
dp[i][j] = min(dp[i][j], cnt);
}
if (matrix[i][j]=='Z'){
if (i-1>0 && !dfs(i-1, j, 0)) break;
dp[i][j] = min(dp[i][j], cnt);
}
visited[i][j] = 1e9;
}
}
for (int i=1;i<=n;i++){
for (int i=1;i<=n;i++) fill(visited[i]+1, visited[i]+m+1, 0);
cnt = 0;
for (int j=m;j;j--){
cnt++;
visited[i][j] = 1;
if (matrix[i][j]=='Z'){
if (i+1<=n && !dfs(i+1, j, 1)) break;
dp[i][j] = min(dp[i][j], cnt);
}
if (matrix[i][j]=='N'){
if (i-1>0 && !dfs(i-1, j, 0)) break;
dp[i][j] = min(dp[i][j], cnt);
}
visited[i][j] = 1e9;
}
}
for (int i=1;i<=n;i++){
for (int j=1;j<=m;j++){
int ans = dp[i][j]<<1;
if (ans==2e9) ans = -1;
printf("%d ", ans);
}
printf("\n");
}
return 0;
}
Compilation message (stderr)
sandwich.cpp: In function 'int main()':
sandwich.cpp:37:10: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
37 | scanf("%d %d", &n, &m);
| ~~~~~^~~~~~~~~~~~~~~~~
sandwich.cpp:39:14: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
39 | scanf("%s", matrix[i]+1);
| ~~~~~^~~~~~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |