Advertisement
newb_ie

bfs_grid

Nov 13th, 2021
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2.  
  3. using namespace std;
  4.  
  5. const int maxN = 100;
  6. bool visited[maxN][maxN];
  7. int cost[maxN][maxN];
  8. pair<int,int> parent[maxN][maxN];
  9.  
  10. char grid[maxN][maxN];
  11.  
  12. int dx[4] = {1, 0, -1, 0};
  13. int dy[4] = {0, 1, 0, -1};
  14.  
  15. void bfs (int x,int y, int n, int m) {
  16. queue<pair<int,int>> q;
  17. q.push(make_pair(x, y));
  18. cost[x][y] = 0;
  19. visited[x][y] = true;
  20. while (!q.empty()) {
  21. pair<int,int> u = q.front();
  22. q.pop();
  23. for (int i = 0; i < 4; ++i) {
  24. int dxx = dx[i] + u.first;
  25. int dyy = dy[i] + u.second;
  26. if (dxx >= 1 and dxx <= n and dyy >= 1 and dyy <= m and grid[dxx][dyy] != '#' and !visited[dxx][dyy]) {
  27. visited[dxx][dyy] = true;
  28. cost[dxx][dyy] = cost[u.first][u.second] + 1;
  29. q.push(make_pair(dxx, dyy));
  30. parent[dxx][dyy] = u;
  31. }
  32. }
  33. }
  34. }
  35.  
  36. int main () {
  37. int n, m;
  38. cin >> n >> m;
  39. int xx, yy, x, y;
  40. for (int i = 1; i <= n; ++i) {
  41. for (int j = 1; j <= m; ++j) {
  42. cin >> grid[i][j];
  43. if (grid[i][j] == 'A') {
  44. x = i, y = j;
  45. }
  46. if (grid[i][j] == 'B') {
  47. xx = i, yy = j;
  48. }
  49. }
  50. }
  51. bfs(x, y, n, m);
  52. cout << cost[xx][yy] << '\n';
  53. }
  54.  
  55.  
  56.  
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement