Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdio>
- #include <fstream>
- #include <vector>
- #include <algorithm>
- #include <set>
- #include <queue>
- #include <cstring>
- using namespace std;
- const int INF = 100000;
- bool check(int ii, int jj, int i, int j, int m, int n, vector<vector<char>> &a, vector<vector<int> > &res){ // проверка на границы
- if(ii < 0)
- return 0;
- if(ii >= m)
- return 0;
- if(jj < 0)
- return 0;
- if(jj >= n)
- return 0;
- if(a[ii][jj] == 'X')
- return 0;
- if(res[ii][jj] < res[i][j])
- return 0;
- return 1;
- }
- int main() {
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- vector<vector<char>> a;
- vector<vector<int> > res;
- int m, n;
- cin >> m >> n;
- int i, j;
- a.resize(100, vector<char> (100));
- res.resize(100, vector<int> (100, 100000));
- int idxi = 101, idxj;
- queue<pair<int, int>> q;
- for(i = 0; i < m; i++){
- for(j = 0; j < n; ++j){
- cin >> a[i][j];
- if(a[i][j] == 'S'){
- q.push(make_pair(i, j));
- res[i][j] = 0;
- }
- if(a[i][j] == 'F'){
- idxi = i;
- idxj = j;
- }
- }
- }
- while(q.size()){ // обход в ширину
- auto t = q.front();
- i = t.first;
- j = t.second;
- if(check(i, j - 1, i, j, m, n, a, res)){
- res[i][j - 1] = res[i][j] + 1;
- q.push(make_pair(i, j - 1));
- }
- if(check(i, j + 1, i, j, m, n, a, res)){
- res[i][j + 1] = res[i][j] + 1;
- q.push(make_pair(i, j + 1));
- }
- if(check(i + 1, j, i, j, m, n, a, res)){
- res[i + 1][j] = res[i][j] + 1;
- q.push(make_pair(i + 1, j));
- }
- if(check(i - 1, j, i, j, m, n, a, res)){
- res[i - 1][j] = res[i][j] + 1;
- q.push(make_pair(i - 1, j));
- }
- q.pop();
- }
- if(res[idxi][idxj] == 100000){
- cout << -1;
- }
- else{
- cout << res[idxi][idxj];
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement