Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <deque>
- #include <utility>
- #include <algorithm>
- using namespace std;
- int main() {
- int n, m;
- char c;
- cin >> n >> m;
- vector <vector<int>> a(n + 2, vector<int>(m + 2, -2));
- deque<pair <int, int>> deq;
- int xi = -1, xj = -1, yi = -1, yj = -1;
- for (int i = 1; i < n + 1; i++)
- for (int j = 1; j < m + 1; j++) {
- cin >> c;
- if (c == 's') {
- a[i][j] = 0;
- deq.push_back(pair <int, int>(i, j));
- xi = i;
- xj = j;
- }
- else if (c == 'f') {
- yi = i;
- yj = j;
- a[i][j] = -1;
- }
- else if (c == '.')
- a[i][j] = -1;
- }
- while (!deq.empty()) {
- pair <int, int> p (deq.front());
- deq.pop_front();
- if (a[p.first - 1][p.second] == -1) {
- a[p.first - 1][p.second] = a[p.first][p.second] + 1;
- deq.push_back(pair<int, int>(p.first - 1, p.second));
- }
- if (a[p.first][p.second + 1] == -1) {
- a[p.first][p.second + 1] = a[p.first][p.second] + 1;
- deq.push_back(pair<int, int>(p.first, p.second + 1));
- }
- if (a[p.first + 1][p.second] == -1) {
- a[p.first + 1][p.second] = a[p.first][p.second] + 1;
- deq.push_back(pair<int, int>(p.first + 1, p.second));
- }
- if (a[p.first][p.second - 1] == -1) {
- a[p.first][p.second - 1] = a[p.first][p.second] + 1;
- deq.push_back(pair<int, int>(p.first, p.second - 1));
- }
- }
- if (a[yi][yj] == -1) {
- cout << -1;
- }
- else {
- bool flag = false;
- if (xi == yi) {
- for (int i = 1; i < n + 1; i++)
- for (int j = 1; j < m + 1; j++)
- if (a[i][j] != -1 && (i != yi)) {
- flag = true;
- break;
- }
- }
- else if (xj == yj) {
- for (int i = 1; i < n + 1; i++)
- for (int j = 1; j < m + 1; j++)
- if (a[i][j] != -1 && (j != yj)) {
- flag = true;
- break;
- }
- }
- if (flag == false)
- cout << (abs(xi - yi) + abs(xj - yj)) % 2;
- else {
- if (xi == yi)
- cout << abs(xj - yj);
- else cout << abs(xi - yi);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement