Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <vector>
- #include <queue>
- #include <algorithm>
- using namespace std;
- int main()
- {
- int n, m;
- cin >> n >> m;
- char mat[n][m];
- int si = 0, sj = 0;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cin >> mat[i][j];
- if(mat[i][j] == 'S') {
- si = i;
- sj = j;
- }
- }
- }
- int dist[n][m]; // ke ni zapisuva kolkav e najkratiot pat od poleto S do poleto (i, j)
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- dist[i][j] = -1;
- }
- }
- dist[si][sj] = 0;
- queue<int> q;
- q.push(si);
- q.push(sj);
- 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();
- for(int k = 0; k < 4; k++) {
- int ti = ci + di[k];
- int tj = cj + dj[k];
- if(ti >= 0 and ti < n and tj >= 0 and tj < m and mat[ti][tj] != '#' and dist[ti][tj] == -1) {
- dist[ti][tj] = dist[ci][cj] + 1;
- q.push(ti);
- q.push(tj);
- }
- }
- }
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cout << dist[i][j] << " ";
- }
- cout << endl;
- }
- return 0;
- }
- /*
- 4 4
- ####
- ..##
- S...
- ####
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement