Advertisement
wym1111

Untitled

Feb 27th, 2024
712
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define int long long
  5. #define endl '\n'
  6. using ll = long long;
  7.  
  8. const int N = 1e3 + 5;
  9.  
  10. int n, m;
  11. int a[N][N];
  12. int dis[N][N];
  13. bool vis[N][N];
  14.  
  15. int dx[2] = {2, 1};
  16. int dy[2] = {0, 1};
  17.  
  18. struct str {
  19.     int x, y;
  20.     int d;
  21.     bool operator < (const str & tmp) const {
  22.         return d > tmp.d;
  23.     }
  24. };
  25.  
  26. void bfs () {
  27.     for (int i = 0; i < n; i ++) {
  28.         for (int j = 0; j < m; j ++) {
  29.             dis[i][j] = 1e8;
  30.             vis[i][j] = 0;
  31.         }
  32.     }
  33.     priority_queue<str> q;
  34.     q.push({0, 0, 0});
  35.     dis[0][0] = 0;
  36.     while (!q.empty()) {
  37.         int x = q.top().x, y = q.top().y;
  38.         q.pop();
  39.         if (vis[x][y]) continue;
  40.         vis[x][y] = 1;
  41. //      cout << x << ',' << y << "  " << dis[x][y] << endl;
  42.         for (int i = 0; i < 2; i ++) {
  43.             int nx = (x + dx[i]) % n;
  44.             int ny = y + dy[i];
  45. //          cout << nx << ' ' << ny << endl;
  46.             if (vis[nx][ny] || ny >= m || a[nx][ny]) continue;
  47.             if (i == 0 && a[(x + 1) % n][ny]) continue;
  48.             if (dis[x][y] + 1 < dis[nx][ny]) {
  49.                 dis[nx][ny] = dis[x][y] + 1;
  50.                 q.push({nx, ny, dis[nx][ny]});
  51.             }
  52.         }
  53.     }
  54. }
  55.  
  56. void solve() {
  57.     cin >> n >> m;
  58.     for (int i = 0; i < n; i ++) {
  59.         for (int j = 0; j < m; j ++) {
  60.             cin >> a[i][j];
  61.         }
  62.     }
  63.     bfs();
  64.     int ans = 1e8;
  65.     for (int i = 0; i < n; i ++) {
  66.         if (dis[i][m - 1] >= ans) continue;
  67.         int tmp = (i + n - dis[i][m - 1] % n) % n;
  68.         ans = min(ans, dis[i][m - 1] + min(n - 1 - tmp, tmp + 1));
  69. //      cout << i << ' ' << dis[i][m - 1] << "  " << tmp << endl;
  70.     }
  71.     if (ans == 1e8) cout << -1 << endl;
  72.     else cout << ans << endl;
  73. }
  74.  
  75. signed main() {
  76.     ios::sync_with_stdio(false);
  77.     cin.tie(nullptr);
  78.     int _ = 1;
  79.     cin >> _;
  80.     while (_--) {
  81.         solve();
  82.     }
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement