fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long ll;
  5. typedef pair<int, int> pii;
  6.  
  7. #define FOR(i,a,b) for(int i=a; i<=b; ++i)
  8. #define FORR(i,a,b) for(int i=a; i>=b; --i)
  9. #define pb push_back
  10. #define mp make_pair
  11. #define fi first
  12. #define se second
  13. #define all(x) x.begin(), x.end()
  14. #define sz(x) x.size()
  15.  
  16. template<class T>
  17. bool maximize(T &a, T b) {
  18. if (a < b) {a = b; return true;}
  19. return false;
  20. }
  21.  
  22. template<class T>
  23. bool minimize(T &a, T b) {
  24. if (a > b) {a = b; return true;}
  25. return false;
  26. }
  27.  
  28. const int inf = INT_MAX;
  29. const ll LLinf = LONG_LONG_MAX;
  30. const int MOD = 1e9 + 7;
  31. const int N = 100 + 5;
  32. const int dx[] = {0, 0, 1, -1}; // (x+0, x+0, x+1, x-1)
  33. const int dy[] = {1, -1, 0, 0}; // (y+1, y-1, y+0, y+0)
  34.  
  35. int dist[N][N];
  36. char a[N][N];
  37.  
  38. void solve(){
  39. int n, m;
  40. cin >> n >> m;
  41. queue<pair<int, int>> q; // lưu các ô (i, j)
  42. memset(dist, 0x3f, sizeof dist); // +oo
  43. FOR(i,1,n)
  44. FOR(j,1,m){
  45. cin >> a[i][j];
  46. if (a[i][j] == 'C') dist[i][j] = 0, q.push(mp(i, j));
  47. }
  48. while(!q.empty()){
  49. int x = q.front().fi;
  50. int y = q.front().se;
  51. q.pop();
  52. if (a[x][y] == 'B') cout << dist[x][y], exit(0);
  53. FOR(i,0,3){
  54. int x1 = x + dx[i];
  55. int y1 = y + dy[i];
  56. if (x1 > 0 && x1 <= n && y1 > 0 && y1 <= m && dist[x1][y1] > dist[x][y] && a[x1][y1] != '*')
  57. dist[x1][y1] = dist[x][y] + 1, q.push(mp(x1, y1));
  58. }
  59. }
  60. cout << -1;
  61. }
  62.  
  63. main(){
  64. // icebear hehehhe
  65. cin.tie(0) -> sync_with_stdio(0);
  66. cout.tie(0);
  67. int t = 1;
  68. while(t--) solve();
  69. return 0;
  70. }
  71.  
Success #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
-1