#include #include #define UP 0 #define RIGHT 1 #define DOWN 2 #define LEFT 3 char program[10]; int W,H; char *mapa; char *mem; int pl; // program length typedef struct { char w,h; char heading; char pc; } state; int state_to_idx(state s) { //printf("checking state %d: %d\n", s.w + s.h*W + s.pc*(W*H) + s.heading*(W*H*pl), mem[s.w + s.h*W + s.pc*(W*H) + s.heading*(W*H*pl)]); return s.w + s.h*W + s.pc*(W*H) + s.heading*(W*H*pl); } int is_free(int x, int y) { if ((x<0) || (y<0) || (x>=W) || (y>=H)) return 0; if (mapa[x*W+y] == '.') return 1; else return 0; } void proc_state(state s) { int idx = state_to_idx(s); if (!mem[idx]) { mem[idx] = 1; } else return; int pc0 = (s.pc+(pl-1))%pl; switch (program[s.pc]) { case 'L': proc_state(state {s.w, s.h, (s.heading+1)%4, pc0}); break; case 'R': proc_state(state {s.w, s.h, (s.heading+3)%4, pc0}); break; case 'S': proc_state(s); int x = s.w, y=s.h; switch (s.heading) { case LEFT: if (!is_free(s.w-1, s.h)) proc_state(state {s.w, s.h, s.heading, pc0}); if (is_free(s.w+1, s.h)) proc_state(state {s.w+1, s.h, s.heading, pc0}); break; case RIGHT: if (!is_free(s.w+1, s.h)) proc_state(state {s.w, s.h, s.heading, pc0}); if (is_free(s.w-1, s.h)) proc_state(state {s.w-1, s.h, s.heading, pc0}); break; case UP: if (!is_free(s.w, s.h-1)) proc_state(state {s.w, s.h, s.heading, pc0}); if (is_free(s.w, s.h+1)) proc_state(state {s.w, s.h+1, s.heading, pc0}); break; case DOWN: if (!is_free(s.w, s.h+1)) proc_state(state {s.w, s.h, s.heading, pc0}); if (is_free(s.w, s.h-1)) proc_state(state {s.w, s.h-1, s.heading, pc0}); } proc_state(state {x, y, s.heading, pc0}); } } int main() { while (scanf("%d %d\n",&H,&W) == 2) { int exit_x, exit_y; int total_dots = 1; // vstup programu //printf("W,H: %d %d\n", W,H); mapa = (char*)malloc(W*H); for (int j = 0; j < H; j++) { for (int i = 0; i < W; i++) { scanf("%c", mapa+j*W+i); //printf("%c", mapa[j*W+i]); if (mapa[j*W+i] == 'E') { exit_x = i; exit_y = j; } else if (mapa[j*W+i] == '.') total_dots+=1; } scanf("\n"); //printf("\n"); } scanf("%d\n", &pl); //printf("program len: %d\n", pl); for (int i = 0; i < pl; i++) { scanf("%c", program+i); //printf("%c", program[i]); } // allocate the memoization memory mem = (char*)calloc(W*H*pl*4, sizeof(char)); //printf("allocated W*H*pl*4=%d bytes.\n", W*H*pl*4); // mark the exit node as complete //printf("exit node: %d, %d\n", exit_x, exit_y); for (int h = 0; h < 4; h++) { for (int p = 0; p < pl; p++) { state s = state {exit_x, exit_y, h, p}; proc_state(s); } } // check the board for completeness int count = 1; for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { int reachable = 0; for (int p = 0; p < pl; p++) { if ((mapa[y*W+x] != '.') || (mem[state_to_idx(state {x,y,UP,p})])) { if (mapa[y*W+x] == '.') { count += 1; } reachable = 1; break; } } //printf("result for %d, %d: %d\n", x, y, count); //printf("dots: %d\n", total_dots); } } if (count == total_dots) printf("OK\n"); else printf("%d\n", count); free(mapa); free(mem); } }