Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- #include <cstring>
- using namespace std;
- int main() {
- int redovi, koloni;
- cin >> redovi >> koloni;
- char lavirint[redovi][koloni];
- int poseteno[redovi][koloni];
- int sashe[redovi][koloni]; // ni kazuva dali mozeme da stigneme od kukjata na sashe do ova pole i vo kolku cekori
- int elena[redovi][koloni];
- for(int i = 0; i < redovi; i++) {
- for(int j = 0; j < koloni; j++) {
- sashe[i][j] = -1;
- elena[i][j] = -1;
- }
- }
- int si, sj; // kaj se naoga kukjata na sashe
- int ei, ej; // kaj se naoga kukjata na elena
- 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] == 'E') {
- ei = i;
- ej = j;
- }
- }
- }
- int di[] = {+1, -1, 0, 0};
- int dj[] = {0, 0, - 1, +1};
- memset(poseteno, 0, sizeof poseteno);
- 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 cekor = Q.front();
- Q.pop();
- if(lavirint[ci][cj] == 'E') {
- cout << cekor << endl;
- return 0;
- }
- for(int k = 0; k < 4; k++) {
- int ti = ci + di[k];
- int tj = cj + dj[k];
- if(ti >= 0 and ti < redovi and tj >= 0 and tj < koloni and poseteno[ti][tj] == 0) {
- if(lavirint[ti][tj] == '#') {
- sashe[ti][tj] = cekor + 1;
- poseteno[ti][tj] = 1;
- }
- else {
- Q.push(ti);
- Q.push(tj);
- Q.push(cekor + 1);
- poseteno[ti][tj] = 1;
- }
- }
- }
- }
- memset(poseteno, 0, sizeof poseteno);
- queue<int> Q2;
- Q2.push(ei);
- Q2.push(ej);
- Q2.push(0);
- poseteno[ei][ej] = 1;
- while(Q2.size() > 0) {
- int ci = Q2.front();
- Q2.pop();
- int cj = Q2.front();
- Q2.pop();
- int cekor = Q2.front();
- Q2.pop();
- for(int k = 0; k < 4; k++) {
- int ti = ci + di[k];
- int tj = cj + dj[k];
- if(ti >= 0 and ti < redovi and tj >= 0 and tj < koloni and poseteno[ti][tj] == 0) {
- if(lavirint[ti][tj] == '#') {
- elena[ti][tj] = cekor + 1;
- poseteno[ti][tj] = 1;
- }
- else {
- Q2.push(ti);
- Q2.push(tj);
- Q2.push(cekor + 1);
- poseteno[ti][tj] = 1;
- }
- }
- }
- }
- int najgolem_pat = -1;
- for(int i = 0; i < redovi; i++) {
- for(int j = 0; j < koloni; j++) {
- if(lavirint[i][j] == '#') {
- if(elena[i][j] != -1 and sashe[i][j] != -1) {
- if(najgolem_pat < elena[i][j] + sashe[i][j]) {
- najgolem_pat = elena[i][j] + sashe[i][j];
- }
- }
- }
- }
- }
- cout << najgolem_pat << endl;
- return 0;
- }
- /*
- S..#E
- ###..
- #....
- .....
- **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement