Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- using namespace std;
- int redovi, koloni;
- char lavirint[1000][1000];
- int bfs(int si, int sj, int ei, int ej) {
- int poseteno[redovi][koloni];
- for(int i = 0; i < redovi; i++) {
- for(int j = 0; j < koloni; j++) {
- poseteno[i][j] = 0;
- }
- }
- queue<int> Q;
- Q.push(si);
- Q.push(sj);
- Q.push(0);
- poseteno[si][sj] = 1;
- while(Q.size() > 0) {
- int ci = Q.front();
- Q.pop();
- int cj = Q.front();
- Q.pop();
- int cekori = Q.front();
- Q.pop();
- if(ci == ei and cj == ej) {
- return cekori;
- }
- if(ci + 1 < redovi and lavirint[ci + 1][cj] != '#' and poseteno[ci + 1][cj] == 0) {
- Q.push(ci + 1);
- Q.push(cj);
- Q.push(cekori + 1);
- poseteno[ci + 1][cj] = 1;
- }
- if(ci - 1 >= 0 and lavirint[ci - 1][cj] != '#' and poseteno[ci - 1][cj] == 0) {
- Q.push(ci - 1);
- Q.push(cj);
- Q.push(cekori + 1);
- poseteno[ci - 1][cj] = 1;
- }
- if(cj + 1 < koloni and lavirint[ci][cj + 1] != '#' and poseteno[ci][cj + 1] == 0) {
- Q.push(ci);
- Q.push(cj + 1);
- Q.push(cekori + 1);
- poseteno[ci][cj + 1] = 1;
- }
- if(cj - 1 >= 0 and lavirint[ci][cj - 1] != '#' and poseteno[ci][cj - 1] == 0) {
- Q.push(ci);
- Q.push(cj - 1);
- Q.push(cekori + 1);
- poseteno[ci][cj - 1] = 1;
- }
- }
- return 0;
- }
- int main()
- {
- cin >> redovi >> koloni;
- int si, sj;
- int ai, aj;
- int bi, bj;
- int pi, pj;
- for(int i = 0; i < redovi; i++) {
- for(int j = 0; j < koloni; j++) {
- cin >> lavirint[i][j];
- if(lavirint[i][j] == 'S') {
- si = i;
- sj = j;
- }
- if(lavirint[i][j] == 'A') {
- ai = i;
- aj = j;
- }
- if(lavirint[i][j] == 'B') {
- bi = i;
- bj = j;
- }
- if(lavirint[i][j] == 'P') {
- pi = i;
- pj = j;
- }
- }
- }
- int pat1 = bfs(si, sj, ai, aj) + bfs(ai, aj, pi, pj);
- int pat2 = bfs(si, sj, bi, bj) + bfs(bi, bj, pi, pj);
- if(pat1 < pat2) {
- cout << pat1 << endl;
- }
- else {
- cout << pat2 << endl;
- }
- return 0;
- }
- /*
- 8 8
- S...#..A
- ........
- ...#P...
- B.......
- ##......
- ########
- ........
- ........
- **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement