Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define MAX 102
- using namespace std;
- int n, m;
- int cx, cy, px, py, lx, ly;
- char mat[MAX][MAX];
- struct solve {
- int x;
- int y;
- int d;
- solve(int x1, int y1, int d1) : x(x1), y(y1), d(d1) {}
- };
- bool norte(int x, int y) {
- if((x-1) >= 0) return mat[x-1][y] != '*';
- else return false;
- }
- bool sur(int x, int y) {
- if((x+1) < n) return mat[x+1][y] != '*';
- else return false;
- }
- bool este(int x, int y) {
- if((y+1) < m) return mat[x][y+1] != '*';
- else return false;
- }
- bool oeste(int x, int y) {
- if((y-1) >= 0) return mat[x][y-1] != '*';
- else return false;
- }
- int bfs(int origenX, int origenY, int destinoX, int destinoY) {
- bool v[MAX][MAX];
- memset(v, false, sizeof(v));
- solve ini(origenX, origenY, 0);
- queue <solve> cola;
- cola.push(ini);
- while(!cola.empty()) {
- solve now = cola.front();
- cola.pop();
- if(now.x == destinoX && now.y == destinoY) return now.d;
- if(v[now.x][now.y]) continue;
- v[now.x][now.y] = true;
- if(norte(now.x, now.y)) {
- solve r(now.x-1, now.y, now.d+1);
- cola.push(r);
- }
- if(sur(now.x, now.y)) {
- solve r(now.x+1, now.y, now.d+1);
- cola.push(r);
- }
- if(este(now.x, now.y)) {
- solve r(now.x, now.y+1, now.d+1);
- cola.push(r);
- }
- if(oeste(now.x, now.y)) {
- solve r(now.x, now.y-1, now.d+1);
- cola.push(r);
- }
- }
- return -1;
- }
- int main() {
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- cin >> n >> m;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cin >> mat[i][j];
- if(mat[i][j] == 'c') cx = i, cy = j;
- if(mat[i][j] == 'p') px = i, py = j;
- if(mat[i][j] == 'l') lx = i, ly = j;
- }
- }
- int r1 = bfs(cx, cy, lx, ly);
- int r2 = bfs(lx, ly, px, py);
- if(r1 != -1 && r2 != -1) cout << r1 + r2;
- else cout << -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement