Advertisement
Korotkodul

bfs лабиринт 13 WA рассмотри контр-тест с множеством препятствий

Jan 17th, 2022 (edited)
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <queue>
  5. #include <algorithm>
  6. #include <string>
  7. #include <stack>
  8. #include <set>
  9. #include <map>
  10. #define pii pair <int,int>
  11. #define vec vector
  12. using namespace std;
  13. using ll = long long;
  14. using ld = long double;
  15. using db = double;
  16. void cv(vector <int> &v){
  17. for (auto x: v) cout<<x<<' ';
  18. cout<<"\n";
  19. }
  20.  
  21. void cvl(vector <ll> &v){
  22. for (auto x: v) cout<<x<<' ';
  23. cout<<"\n";
  24. }
  25.  
  26.  
  27. void cvv(vector <vector <int> > &v){
  28. for (auto x: v) cv(x);
  29. cout<<"\n";
  30. }
  31. int n,m;
  32. vector <vector <int> > dsk;
  33. bool gd(pii p){
  34. int x = p.first, y = p.second;
  35. return x < n && x >=0 && y >= 0 && y < m && dsk[x][y] != 1;
  36. }
  37. const int inf = 2e9;
  38. vector <vector <int> > dist;
  39. queue <pii> Q;
  40.  
  41. int D(pii v){
  42. return dist[v.first][v.second];
  43. }
  44.  
  45. void bfs(){
  46. Q.push({0,0});
  47. dist[0][0] = 0;
  48. pii v,u;
  49. while (!Q.empty()){
  50. v = Q.front();
  51. Q.pop();
  52. //вверх
  53. u = v;
  54. while (gd({u.first-1, u.second})){
  55. u.first--;
  56. }
  57. if (D(u) == inf){
  58. dist[u.first][u.second] = D(v) + 1;
  59. Q.push(u);
  60. }
  61. //вниз
  62. u = v;
  63. while (gd({u.first+1, u.second})) u.first++;
  64. if (D(u) == inf){
  65. dist[u.first][u.second] = D(v) + 1;
  66. Q.push(u);
  67. }
  68. //влево
  69. u = v;
  70. while (gd({u.first, u.second-1})){
  71. u.second--;
  72. }
  73. if (D(u) == inf){
  74. dist[u.first][u.second] = D(v) + 1;
  75. Q.push(u);
  76. }
  77. //вправо
  78. u = v;
  79. while (gd({u.first, u.second+1})) u.second++;
  80. if (D(u) == inf) {
  81. dist[u.first][u.second] = D(v) + 1;
  82. Q.push(u);
  83. }
  84. }
  85. }
  86.  
  87. int main()
  88. {
  89. ios::sync_with_stdio(0);
  90. cin.tie(0);
  91. cout.tie(0);
  92. cin>>n>>m;
  93. dsk.assign(n, vector <int> (m, 0));
  94. dist.assign(n, vector <int> (m , inf));
  95. for (int i=0;i<n;++i) for (int j = 0; j < m;++j) cin>>dsk[i][j];
  96. bfs();
  97. vector <int> ans;
  98. for (int i=0;i<n;++i) {
  99. for (int j=0;j<m;++j){
  100. if (dsk[i][j] == 2){
  101. ans.push_back(dist[i][j]);
  102. }
  103. }
  104. }
  105. sort(ans.begin(), ans.end());
  106. cout<<ans[0]<<"\n";
  107. }
  108.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement