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
| #include <bits/stdc++.h> #define re register
using namespace std;
const int N = 1010,inf = 1e9 + 10; int n,m; int arr[N][N],vis[N][N];
struct point{ int x,y; };
inline int read(){ int r = 0,w = 1; char c = getchar(); while (c < '0' || c > '9'){ if (c == '-') w = -1; c = getchar(); } while (c >= '0' && c <= '9'){ r = (r << 3) + (r << 1) + (c ^ 48); c = getchar(); } return r * w; }
inline void bfs(int x,int y){ queue<point> q; vis[x][y] = 0; q.push({x,y}); while (!q.empty()){ point u = q.front(); q.pop(); if (!arr[(u.x + 1) % n][u.y] && !arr[(u.x + 2) % n][u.y]){ int tx = (u.x + 2) % n,ty = u.y; if (!~vis[tx][ty]){ vis[tx][ty] = vis[u.x][u.y] + 1; q.push({tx,ty}); } } if (u.y + 1 < m && !arr[(u.x + 1) % n][u.y + 1]){ int tx = (u.x + 1) % n,ty = u.y + 1; if (!~vis[tx][ty]){ vis[tx][ty] = vis[u.x][u.y] + 1; q.push({tx,ty}); } } } }
inline int calc(int x,int tim){ if (!~tim) return inf; int y = (n - 1 + tim) % n; return tim + min((x - y + n) % n,(y - x + n) % n); }
inline void solve(){ int ans = inf; n = read(),m = read(); for (re int i = 0;i < n;i++){ for (re int j = 0;j < m;j++){ vis[i][j] = -1; arr[i][j] = read(); } } bfs(0,0); for (re int i = 0;i < n;i++) ans = min(ans,calc(i,vis[i][m - 1])); if (ans >= inf) puts("-1"); else printf("%d\n",ans); }
int main(){ int T; T = read(); while (T--) solve(); return 0; }
|