Untitled

 avatar
meda
c_cpp
2 months ago
2.8 kB
15
Indexable
#include<bits/stdc++.h>
#define ll long long
#define endl "\n"
using namespace std;
template<class T>
void printff(vector<T>& v) {
  for (auto k : v) cout << k << " ";
  cout << endl;
}
void SOLVE() {
    int n, m; cin >> n >> m;
    vector<vector<char>> a(n, vector<char>(m));
    for(auto & row : a){
        for(auto & col : row) cin >> col;
    }
    vector<vector<char>> new_grid = a;
    int dx[4] = {1, 0, -1, 0};
    int dy[4] = {0, 1, 0, -1};

    auto isok = [&](int i, int j){
        return (i >= 0 && i < n && j >= 0 && j < m && 
                a[i][j] != '>' && a[i][j] != '>' && a[i][j] != 'v' && a[i][j] != '^');
    };

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (a[i][j] == '>') {
                for(int k = j + 1; k < m; k++)
                    if (isok(i, k)) a[i][k] = '*';
                    else break;
            }
            if (a[i][j] == '<') {
                for(int k = j - 1; k >= 0; k--)
                    if (isok(i, k)) a[i][k] = '*';
                    else break;
            }
            if (a[i][j] == '^') {
                for(int k = i - 1; k >= 0; k--)
                    if (isok(k, j)) a[k][j] = '*';
                    else break;
            }
            if (a[i][j] == 'v') {
                for(int k = i + 1; k < n; k++)
                    if (isok(k, j)) a[k][j] = '*';
                    else break;
            }
        }
    }

    queue<pair<int,int>> q;
    vector<vector<int>> level(n, vector<int>(m, 1e9));
    vector<vector<pair<int,int>>> prev(n, vector<pair<int,int>>(m, {-1, -1}));

    if (a[0][0] == '.') {
        level[0][0] = 0;
        q.push({0, 0});
    }else{
        return void(cout << -1 << endl);
    }
    auto isok2 =[&] (int i, int j){
        return i >= 0 && i < n && j >= 0 && j < m && a[i][j] == '.';
    };
    while(!q.empty()){
        auto [x, y] = q.front();
        q.pop();

        for(int k = 0; k < 4; k++){
            int nx = x + dx[k], ny = y + dy[k];
            if(isok2(nx, ny) && level[nx][ny] == 1e9) {
                level[nx][ny] = level[x][y] + 1;
                prev[nx][ny] = {x, y};
                q.push({nx, ny});
            }
        }
    }
    if(prev[n - 1][m - 1] == make_pair(-1, -1)) return void(cout << -1 << endl);

    pair<int, int> cur = {n - 1, m - 1};
    while (cur != make_pair(-1, -1)) {
        new_grid[cur.first][cur.second] = 'X';
        cur = prev[cur.first][cur.second];
    }

    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++) cout << new_grid[i][j];
        cout << endl;
    }
}
int main() {
  ios_base::sync_with_stdio(false); 
  cin.tie(NULL); 
  cout.tie(NULL);
  int tc = 1; //cin >> tc;
  while(tc--) SOLVE();
  return 0;
}
Leave a Comment