Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- using namespace std;
- int main() {
- int n, m;
- cin >> n >> m;
- char mat[n][m];
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cin >> mat[i][j];
- }
- }
- // prvo da najdeme kade se naoga S i kade se naoga E
- int si = -1, sj = -1;
- int ei = -1, ej = -1;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- if(mat[i][j] == 'S') {
- si = i;
- sj = j;
- }
- if(mat[i][j] == 'E') {
- ei = i;
- ej = j;
- }
- }
- }
- bool visited[n][m]; // ke ni kazuva koi polinja sme gi posetile a koi ne
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- visited[i][j] = false;
- }
- }
- queue<int> q;
- q.push(si);
- q.push(sj);
- q.push(0); // kolku cekori sum napravil od poleto S do momentalnoto pole
- visited[si][sj] = true;
- while(!q.empty()) {
- int ci = q.front();
- q.pop();
- int cj = q.front();
- q.pop();
- int cekori = q.front();
- q.pop();
- if(mat[ci][cj] == 'E') { // ova znaci deka sme stignale do krajot odnosno do posakuvanata destinacija
- cout << "Od S do E ni trebaat " << cekori << " broj na cekori" << endl;
- break;
- }
- if(ci + 1 < n and mat[ci + 1][cj] != '#' and !visited[ci + 1][cj]) { // sosed dole
- q.push(ci + 1);
- q.push(cj);
- q.push(cekori + 1);
- visited[ci + 1][cj] = true; // ne sakame da se vrakame nazad
- }
- if(ci - 1 >= 0 and mat[ci - 1][cj] != '#' and !visited[ci - 1][cj]) { // sosed gore
- q.push(ci - 1);
- q.push(cj);
- q.push(cekori + 1);
- visited[ci - 1][cj] = true;
- }
- if(cj + 1 < m and mat[ci][cj + 1] != '#' and !visited[ci][cj + 1]) {
- q.push(ci);
- q.push(cj + 1);
- q.push(cekori + 1);
- visited[ci][cj + 1] = true;
- }
- if(cj - 1 >= 0 and mat[ci][cj - 1] != '#' and !visited[ci][cj - 1]) {
- q.push(ci);
- q.push(cj - 1);
- q.push(cekori + 1);
- visited[ci][cj - 1] = true;
- }
- }
- return 0;
- }
- /*
- 5 5
- .....
- #####
- S....
- E....
- #####
- 5 5
- #..E#
- .....
- ##...
- S....
- #####
- Queue: (3, 0)
- (3, 0) --> (3, 1)
- Queue: (3, 1)
- (3, 1) --> (3, 2)
- Queue: (3, 2) --> (3, 3); (2, 2)
- Queue(3, 3); (2, 2)
- (3, 3) --> (3, 4); (2, 3)
- Queue: (2, 2), (3, 4), (2, 3)
- (2, 2) --> (1, 2)
- Queue: (3, 4), (2, 3), (1, 2)
- (3, 4) --> (2, 4)
- Queue: (2, 3), (1, 2), (2, 4)
- (2, 3) --> (1, 3)
- Queue: (1, 2), (2, 4), (1, 3)
- (1, 2) --> (1, 1); (0, 2)
- Queue: (2, 4); (1, 3); (1, 1); (0, 2)
- (2, 4) --> (1, 4)
- Queue: (1, 3); (1, 1); (0, 2); (1, 4)
- (1, 3) --> (0, 3)
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement