1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| #include <bits/stdc++.h>
#pragma optimization_level 3 #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimization ("unroll-loops")
#define MAX_N 2020 #define ll long long #define pll pair<ll, ll> #define vpll vector<pll> #define vll vector<ll> #define vs vector<string> #define vvll vector<vll> #define all(a) begin(a), end(a) using namespace std; bool vis[401][401]; ll dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1}; string dir = "NESW";
void merge(vvll& adj, ll fy, ll fx, ll ty, ll tx, ll d) { vpll f{{fy*2, fx*2},{fy*2, fx*2 + 1}, {fy*2 + 1, fx*2 + 1}, {fy*2 + 1, fx*2}}; vpll t{{ty*2, tx*2},{ty*2, tx*2 + 1}, {ty*2 + 1, tx*2 + 1}, {ty*2 + 1, tx*2}};
auto merge = [&] (ll a, ll b) { pll from = f[a], to = t[b]; adj[from.first][from.second] = a; adj[to.first][to.second] = b; };
merge(d, (d + 2) % 4); }
void dfs(vvll& adj, ll y, ll x) { vis[y][x] = true; for(ll i = 0; i < 4; i++) { ll ny = y + dy[i], nx = x + dx[i]; if(0 <= ny*2 and ny*2 < adj.size() and 0 <= nx*2 and nx*2 < adj[ny].size() and adj[ny*2][nx*2] != -1 and !vis[ny][nx]) { merge(adj, y, x, ny, nx, i); dfs(adj, ny, nx); } } }
string solve(vs& grid, ll& n, ll& m) { memset(vis,0,sizeof(vis)); vvll adj(n*2, vll(m*2,0)); ll req = n*2 * m*2; for(ll i = 0; i < n; i++) for(ll j = 0; j < m; j++) if(grid[i][j] == '#') { adj[i * 2][j * 2] = adj[i * 2 + 1][j * 2] = adj[i * 2][j * 2 + 1] = adj[i * 2 + 1][j * 2 + 1] = -1; req -= 4; } else { adj[i * 2][j * 2] = 1; adj[i * 2][j * 2 + 1] = 2; adj[i * 2 + 1][j * 2 + 1] = 3; adj[i * 2 + 1][j * 2] = 0; }
string res = ""; dfs(adj, 0, 0); ll y = 0, x = 0;
do { res.push_back(dir[adj[y][x]]); ll ny = y + dy[adj[y][x]], nx = x + dx[adj[y][x]]; y = ny, x = nx; }while(y | x);
return res.length() == req ? res : "IMPOSSIBLE"; }
int main() { ios_base::sync_with_stdio(0); cin.tie(0); ll tc, n, m; cin>>tc; for(ll i = 1; i <= tc; i++) { cin>>n>>m; vs grid(n); for(ll j = 0; j < n; j++) cin>>grid[j]; cout<<"Case #"<<i<<": "<<solve(grid, n, m)<<'\n'; }
return 0; }
|