Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #include <ext/pb_ds/assoc_container.hpp>
- #include <ext/pb_ds/tree_policy.hpp>
- using namespace std;
- using namespace __gnu_pbds;
- template <typename T>
- using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
- typedef long long ll;
- typedef pair<ll, ll> pll;
- typedef pair<int, int> pii;
- typedef complex<double> point;
- #define X real()
- #define Y imag()
- #define angle(a) (atan2((a).imag(), (a).real()))
- #define vec(a, b) ((b) - (a))
- #define same(p1, p2) (dp(vec(p1, p2), vec(p1, p2)) < EPS)
- #define dp(a, b) ((conj(a) * (b)).real())
- #define cp(a, b) ((conj(a) * (b)).imag())
- #define length(a) (hypot((a).imag(), (a).real()))
- #define normalize(a) (a) / length(a)
- #define rotateO(p, ang) ((p)*exp(point(0, ang)))
- #define rotateA(p, ang, about) (rotateO(vec(about, p), ang) + about)
- #define reflectO(v, m) (conj((v) / (m)) * (m))
- const ll N = 1005;
- const int MOD = 1e5;
- const double EPS = 1e-5;
- const double PI = acos(-1.0);
- int dx[] = {-1, 0, 0, 1};
- int dy[] = {0, -1, 1, 0};
- ll n, m, mat[N][N], dist[N][N];
- bool valid(ll x, ll y)
- {
- return x >= 0 && x < n && y >= 0 && y < m && mat[x][y] == 1;
- }
- int main()
- {
- scanf("%lld %lld", &n, &m);
- queue<pll> Q;
- memset(dist, -1, sizeof(dist));
- for(int i = 0; i < n; i++)
- for(int j = 0; j < m; j++)
- {
- scanf("%lld", &mat[i][j]);
- if(mat[i][j] == 2)
- {
- Q.push({i, j});
- dist[i][j] = 0;
- }
- }
- while(!Q.empty())
- {
- ll x = Q.front().first;
- ll y = Q.front().second;
- Q.pop();
- for(int i = 0; i < 4; i++)
- {
- ll nx = x + dx[i];
- ll ny = y + dy[i];
- if(valid(nx, ny) && (dist[nx][ny] == -1 || dist[nx][ny] > dist[x][y] + 1))
- {
- dist[nx][ny] = dist[x][y] + 1;
- Q.push({nx, ny});
- }
- }
- }
- ll maxx = 0;
- for(int i = 0; i < n; i++)
- for(int j = 0; j < m; j++)
- if(mat[i][j] == 1)
- {
- if(dist[i][j] == -1)
- {
- printf("-1\n");
- return 0;
- }
- else
- maxx = max(maxx, dist[i][j]);
- }
- printf("%lld\n", maxx);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement