Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- typedef long long ll;
- int main() {
- ios_base::sync_with_stdio(false);
- 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];
- }
- }
- bool visited[n][m];
- int si = -1, sj = -1; // redot na S, kolonata na S
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- visited[i][j] = false;
- if(mat[i][j] == 'S') {
- si = i;
- sj = j;
- }
- }
- }
- int di[] = {-1, 1, 0, 0};
- int dj[] = {0, 0, -1,1};
- queue<int> q;
- q.push(si);
- q.push(sj);
- q.push(0);
- visited[si][sj] = true;
- while(!q.empty()) {
- int ci = q.front(); // momentalno i od poleto
- q.pop();
- int cj = q.front(); // momentalno j od poleto
- q.pop();
- int dist = q.front();
- q.pop();
- cout << ci + 1 << " " << cj + 1 << " " << dist << endl;
- if(mat[ci][cj] == 'E') {
- cout << dist << endl;
- break;
- }
- for(int i = 0; i < 4; i++) {
- int ti = ci + di[i];
- int tj = cj + dj[i];
- if(ti < 0 or tj < 0 or ti >= n or tj >= m) continue;
- if(visited[ti][tj]) continue;
- if(mat[ti][tj] == '#') continue;
- visited[ti][tj] = true;
- q.push(ti);
- q.push(tj);
- q.push(dist + 1);
- }
- }
- return 0;
- }
- /*
- #####
- ..S..
- ..#..
- E....
- #####
- visited[n][m]
- Queue: (1, 2, 0)
- visited[1][2] = true;
- (1, 2) --> (1, 3); (1, 1)
- Queue: (1, 3, 1), (1, 1, 1)
- visited[1][3] = true
- visited[1][1] = true
- (1, 3) --> (1, 4); (2, 3)
- Queue: (1, 1, 1); (1, 4, 2); (2, 3, 2)
- visited[1][4] = true;
- visited[2][3] = true;
- (1, 1) --> (1, 0); (2, 1)
- Queue: (1, 4, 2); (2, 3, 2); (1, 0, 2); (2, 1, 2)
- visited[1][0] = true;
- visited[2][1] = true;
- (1, 4) --> (2, 4, 3)
- Queue: (2, 3, 2); (1, 0, 2); (2, 1, 2); (2, 4, 3)
- visited[2][4] = true;
- (2, 3) --> (3, 3, 3)
- Queue: (1, 0, 2); (2, 1, 2); (2, 4, 3): (3, 3, 3)
- visited[3][3] = true;
- QueueL (2, 1, 2); (2, 4, 3); (3, 3, 3)
- (2, 1) --> (2, 0, 3); (3, 1, 3)
- Queue: (2, 4, 3); (3, 3, 3); (2, 0, 3); (3, 1, 3)
- visited[2][0] = true;
- visited[3][1]
- (2, 4) --> (3, 4)
- Queue: (3, 3, 3); (2, 0, 3); (3, 1, 3); (3, 4, 4)
- visited[3][4] = true;
- (3, 3) --> (3, 2)
- QueueL (2, 0, 3); (3, 1, 3); (3, 4, 4); (3, 2, 4)
- visited[3][2] = true;
- (2, 0, 3) --> (3, 0, 4); ANSWER
- **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement