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;
- int di[] = {-1, 1, 0, 0};
- int dj[] = {0, 0,-1, 1};
- 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;
- }
- for(int i = 0; i < 4; i++) {
- int ti = ci + di[i];
- int tj = cj + dj[i];
- if(ti >= 0 and ti < n and tj >= 0 and tj < m and mat[ti][tj] != '#' and !visited[ti][tj]) {
- q.push(ti);
- q.push(tj);
- q.push(cekori + 1);
- visited[ti][tj] = 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