#include using namespace std; using ll = long long; using pll = pair; #define drep(i, cc, n) for (ll i = (cc); i <= (n); ++i) #define rep(i, n) drep(i, 0, n - 1) #define all(a) (a).begin(), (a).end() #define pb push_back #define fi first #define se second mt19937_64 rng(chrono::system_clock::now().time_since_epoch().count()); const ll MOD1000000007 = 1000000007; const ll MOD998244353 = 998244353; const ll MOD[3] = {999727999, 1070777777, 1000000007}; const ll LINF = 1LL << 60LL; const int IINF = (1 << 30) - 1; void solve(){ int h, w; cin >> h >> w; vector> s(h, vector(w)); for(int i=0; i> s[i][j]; vector> ans(h, vector(w, IINF)); for(int j=0; j=0; i--){ //左から走査 { //st1 : value, st2 : pos, st3 : st1->st2への変換点 multiset st1; set st2; set> st3; for(int j=0; j st2 if(!st3.empty()){ while((*st3.begin()).fi == j){ int pos = (*st3.begin()).se; st1.erase(st1.lower_bound(ans[i+1][pos])); st2.insert(-pos); st3.erase(st3.begin()); if(st3.empty()) break; } } // calc ans if(!st1.empty()) ans[i][j] = min(ans[i][j], *st1.begin()); if(!st2.empty()) ans[i][j] = min(ans[i][j], j + *st2.begin()); } } } //右から走査 { //st1 : value, st2 : pos, st3 : st1->st2への変換点 multiset st1; set st2; set> st3; for(int j=w-1; j>=0; j--){ if(s[i][j] == '#'){ st1.clear(); st2.clear(); st3.clear(); }else{ // add under if(ans[i+1][j] != IINF){ st1.insert(ans[i+1][j]); st3.insert({-(j-ans[i+1][j]), j}); } // move st1 -> st2 if(!st3.empty()){ while((*st3.begin()).fi == -j){ int pos = (*st3.begin()).se; st1.erase(st1.lower_bound(ans[i+1][pos])); st2.insert(pos); st3.erase(st3.begin()); if(st3.empty()) break; } } // calc ans if(!st1.empty()) ans[i][j] = min(ans[i][j], *st1.begin()); if(!st2.empty()) ans[i][j] = min(ans[i][j], *st2.begin() - j); } } } } for(int j=0; j> T; while(T--) solve(); }