#include #include #include #include #include #include using namespace std; struct state { int i,j; int d; int pc; bool operator<(const state &rhs) const { if (i < rhs.i) return true; if (j < rhs.j) return true; if (d < rhs.d) return true; if (pc < rhs.pc) return true; return false; } }; int moves[4][2] = { {-1, 0}, {0, 1}, {1,0}, {0,-1} }; state step(state s, string &ins, vector > &maze) { int pc = s.pc; s.pc = (s.pc + 1) % ins.size(); state ns = s; switch (ins[pc]) { case 'L': ns.d = (s.d + 4 - 1) % 4; break; case 'R': ns.d = (s.d + 1) % 4; break; case 'S': ns.i = s.i + moves[s.d][0]; ns.j = s.j + moves[s.d][1]; if (ns.i < 0 || ns.i >= maze.size() || ns.j < 0 || ns.j >= maze[0].size() || maze[ns.i][ns.j] == 'X') { return s; } break; } return ns; } int main() { int H,W; while (cin >> H >> W) { int VINIT = 0; vector > maze(H,vector(W)); for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { cin >> maze[i][j]; if (maze[i][j] != 'X') ++VINIT; } } string ins; int L; cin >> L; cin >> ins; set gstates, ngstates; long cnt = 0; for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { set lstates; if (maze[i][j] == 'X') { continue; } if (maze[i][j] == 'E') { ++cnt; continue; } state s = {i,j, 0, 0}; if (gstates.count(s)) { ++cnt; continue; } bool suc = false; while (!lstates.count(s) && !ngstates.count(s)) { lstates.insert(s); s = step(s, ins, maze); if (maze[s.i][s.j] == 'E') { ++cnt; gstates.insert(lstates.begin(), lstates.end()); suc = true; break; } } if (!suc) ngstates.insert(lstates.begin(), lstates.end()); } } if (cnt == VINIT) { cout << "OK\n"; } else { cout << cnt << "\n"; } } return 0; }