Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "bits/stdc++.h"
- using namespace std;
- const int maxN = 100;
- bool visited[maxN][maxN];
- int cost[maxN][maxN];
- pair<int,int> parent[maxN][maxN];
- char grid[maxN][maxN];
- int dx[4] = {1, 0, -1, 0};
- int dy[4] = {0, 1, 0, -1};
- void bfs (int x,int y, int n, int m) {
- queue<pair<int,int>> q;
- q.push(make_pair(x, y));
- cost[x][y] = 0;
- visited[x][y] = true;
- while (!q.empty()) {
- pair<int,int> u = q.front();
- q.pop();
- for (int i = 0; i < 4; ++i) {
- int dxx = dx[i] + u.first;
- int dyy = dy[i] + u.second;
- if (dxx >= 1 and dxx <= n and dyy >= 1 and dyy <= m and grid[dxx][dyy] != '#' and !visited[dxx][dyy]) {
- visited[dxx][dyy] = true;
- cost[dxx][dyy] = cost[u.first][u.second] + 1;
- q.push(make_pair(dxx, dyy));
- parent[dxx][dyy] = u;
- }
- }
- }
- }
- int main () {
- int n, m;
- cin >> n >> m;
- int xx, yy, x, y;
- for (int i = 1; i <= n; ++i) {
- for (int j = 1; j <= m; ++j) {
- cin >> grid[i][j];
- if (grid[i][j] == 'A') {
- x = i, y = j;
- }
- if (grid[i][j] == 'B') {
- xx = i, yy = j;
- }
- }
- }
- bfs(x, y, n, m);
- cout << cost[xx][yy] << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement