1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
#include <bits/stdc++.h>

using namespace std;

#define f   first
#define s   second

vector<vector<char>> graph;
vector<pair<int, int>> tiles;
map<char, pair<int, int>> directions{{'G', {-1, 0}}, {'D', {1, 0}}, {'L', {0, -1}}, {'P', {0, 1}}};

void Input();
void makeMoves(char dir);
void makeMove(int tile_nb, char dir);
bool canMakeMove(int i, int j, char dir);
void printSolution();

int main() {
    cin.tie(0);
    ios::sync_with_stdio(0);
    Input();
    int moves_nb;
    cin >> moves_nb;
    while (moves_nb--) {
        char dir;
        cin >> dir;
        makeMoves(dir);
    }
    printSolution();
    return 0;
}

void Input() {
    int rows, columns;
    cin >> rows >> columns;
    graph = vector<vector<char>>(rows, vector<char>(columns));
    int nb_tiles = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            cin >> graph[i][j];
            if (graph[i][j] != '.') {
                nb_tiles++;
            }
        }
    }
    int iter = 0;
    tiles = vector<pair<int, int>>(nb_tiles);
    for (int i = 0; i < rows && iter < nb_tiles; i++) {
        for (int j = 0; j < columns && iter < nb_tiles; j++) {
            if (graph[i][j] != '.') {
                tiles[iter++] = {i, j};
            }
        }
    }
}

void makeMoves(char dir) {
    sort(tiles.begin(), tiles.end());
    if (dir == 'L' || dir == 'G') {
        for (int i = 0; i < tiles.size(); i++) {
            makeMove(i, dir);
        }
    } else {
        for (int i = tiles.size() - 1; i >= 0; i--) {
            makeMove(i, dir);
        }
    }
}

void makeMove(int tile_nb, char dir) {
    int i = tiles[tile_nb].f;
    int j = tiles[tile_nb].s;
    int new_i = -1;
    int new_j = -1;
    int tmp_i = i;
    int tmp_j = j;
    while (canMakeMove(tmp_i, tmp_j, dir)) {
        new_i = tmp_i + directions[dir].f;
        new_j = tmp_j + directions[dir].s;
        tmp_i = new_i;
        tmp_j = new_j;
    }
    if (new_i != -1) {
        swap(graph[i][j], graph[new_i][new_j]);
        tiles[tile_nb] = {new_i, new_j};
    }
}

bool canMakeMove(int i, int j, char dir) {
    int new_i = i + directions[dir].f;
    int new_j = j + directions[dir].s;
    if (new_i >= 0 && new_i < graph.size() && new_j >= 0 && new_j < graph[new_i].size() && graph[new_i][new_j] == '.') {
        return true;
    }
    return false;
}

void printSolution() {
    for (int i = 0; i < graph.size(); i++) {
        for (int j = 0; j < graph[i].size(); j++) {
            cout << graph[i][j];
        }
        cout << endl;
    }
}