Advertisement
LEGEND2004

bfs

Apr 21st, 2024
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. #pragma GCC optimize("O3")
  2. #include <bits/stdc++.h>
  3. #include <ext/pb_ds/assoc_container.hpp>
  4. using namespace std;
  5. using namespace __gnu_pbds;
  6.  
  7. #define ln '\n'
  8. #define int long long
  9. #define double long double
  10. typedef tree<int , null_type , less<int> , rb_tree_tag , tree_order_statistics_node_update> indexed_set;
  11. typedef tree<int , null_type , less_equal<int> , rb_tree_tag , tree_order_statistics_node_update> indexed_multiset;
  12. #define _FastIO ios_base::sync_with_stdio(0); cin.tie(0)
  13. #define pii pair<int , int>
  14. #define pb push_back
  15. #define vi vector<int>
  16. #define mp make_pair
  17. #define lb lower_bound
  18. #define ub upper_bound
  19. #define sz(x) (int)((x).size())
  20. #define all(x) (x).begin() , (x).end()
  21. #define rall(x) (x).rbegin() , (x).rend()
  22. #define F first
  23. #define S second
  24. const int mod = 1e9 + 7;
  25. const int N = 1e3 + 5;
  26. const int INF = (int)2e18 + 123;
  27.  
  28. int dx[4] = {1 , -1 , 0 , 0};
  29. int dy[4] = {0 , 0 , 1 , -1};
  30. int n , m;
  31. char a[N][N];
  32. int d[N][N] , p[N][N];
  33.  
  34. void bfs(int nodei , int nodej){
  35. queue<pii> q;
  36. q.push({nodei , nodej});
  37. d[nodei][nodej] = 0;
  38. while(!q.empty()){
  39. int fromi = q.front().F , fromj = q.front().S;
  40. q.pop();
  41. cout << fromi << " " << fromj << '\n';
  42. for(int i = 0; i < 4; i++){
  43. int x = fromi + dx[i];
  44. int y = fromj + dy[i];
  45. if(x < 1 || y < 1 || x > n || y > m) continue;
  46. if((d[x][y] > d[fromi][fromj] + 1) || a[x][y] == '#') continue;
  47. cout << "ok" << '\n';
  48. d[x][y] = d[fromi][fromj] + 1;
  49. p[x][y] = i;
  50. q.push({x , y});
  51. }
  52. }
  53. }
  54.  
  55. void solve(){
  56. cin >> n >> m;
  57. int xa , xb , ya , yb;
  58. for(int i = 1; i <= n; i++){
  59. for(int j = 1; j <= m; j++){
  60. cin >> a[i][j];
  61. d[i][j] = INF;
  62. if(a[i][j] == 'A'){
  63. xa = i;
  64. ya = j;
  65. }
  66. if(a[i][j] == 'B'){
  67. xb = i;
  68. yb = j;
  69. }
  70. }
  71. }
  72. bfs(xa , ya);
  73. if(d[xb][yb] == INF){
  74. cout << "NO";
  75. return ;
  76. }
  77. cout << "YES\n" << d[xb][yb] << '\n';
  78. }
  79.  
  80. signed main()
  81. {
  82. _FastIO;
  83. int T = 1;
  84. //cin >> T;
  85. while(T--)
  86. solve();
  87. //system("pause");
  88. }
  89.  
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement