Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <vector>
- #include <queue>
- #include <algorithm>
- #include <string>
- #include <stack>
- #include <set>
- #include <map>
- #define pii pair <int,int>
- #define vec vector
- using namespace std;
- using ll = long long;
- using ld = long double;
- using db = double;
- void cv(vector <int> &v){
- for (auto x: v) cout<<x<<' ';
- cout<<"\n";
- }
- void cvl(vector <ll> &v){
- for (auto x: v) cout<<x<<' ';
- cout<<"\n";
- }
- void cvv(vector <vector <int> > &v){
- for (auto x: v) cv(x);
- cout<<"\n";
- }
- int n,m;
- vector <vector <int> > dsk;
- bool gd(pii p){
- int x = p.first, y = p.second;
- return x < n && x >=0 && y >= 0 && y < m && dsk[x][y] != 1;
- }
- const int inf = 2e9;
- vector <vector <int> > dist;
- queue <pii> Q;
- int D(pii v){
- return dist[v.first][v.second];
- }
- void bfs(){
- Q.push({0,0});
- dist[0][0] = 0;
- pii v,u;
- while (!Q.empty()){
- v = Q.front();
- Q.pop();
- //вверх
- u = v;
- while (gd({u.first-1, u.second})){
- u.first--;
- }
- if (D(u) == inf){
- dist[u.first][u.second] = D(v) + 1;
- Q.push(u);
- }
- //вниз
- u = v;
- while (gd({u.first+1, u.second})) u.first++;
- if (D(u) == inf){
- dist[u.first][u.second] = D(v) + 1;
- Q.push(u);
- }
- //влево
- u = v;
- while (gd({u.first, u.second-1})){
- u.second--;
- }
- if (D(u) == inf){
- dist[u.first][u.second] = D(v) + 1;
- Q.push(u);
- }
- //вправо
- u = v;
- while (gd({u.first, u.second+1})) u.second++;
- if (D(u) == inf) {
- dist[u.first][u.second] = D(v) + 1;
- Q.push(u);
- }
- }
- }
- int main()
- {
- ios::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- cin>>n>>m;
- dsk.assign(n, vector <int> (m, 0));
- dist.assign(n, vector <int> (m , inf));
- for (int i=0;i<n;++i) for (int j = 0; j < m;++j) cin>>dsk[i][j];
- bfs();
- vector <int> ans;
- for (int i=0;i<n;++i) {
- for (int j=0;j<m;++j){
- if (dsk[i][j] == 2){
- ans.push_back(dist[i][j]);
- }
- }
- }
- sort(ans.begin(), ans.end());
- cout<<ans[0]<<"\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement