THIS DECISION IS WRITTEN IN C ++, BUT THE PRINCIPLE HAS THE SAME
If your puzzle is presented
char puzzle[N][N]
declare arrays
int xd[8] = { -1, -1, 0, +1, +1, +1, 0, -1 }; int yd[8] = { 0, -1, -1, -1, 0, +1, +1, +1 };
and then when you want to check if the word "w" can be found in the location (x, y) in the d direction (d between 0 and 7 inclusive), just do
bool wordsearch(const char *w, int x, int y, int d) { if (*w == 0) return true; // end of word if (x<0||y<0||x>=N||y>=N) return false; // out of bounds if (puzzle[y][x] != w[0]) return false; // wrong character // otherwise scan forwards return wordsearch(w + 1, x + xd[d], y + yd[d], d); }
And then the drivers
bool wordsearch(const char *w, int x, int y) { int d; for (d=0;d<8;d++) if (wordsearch(w, x, y, d)) return true; return false; } bool wordsearch(const char *w) { int x, y; for (x=0;x<N;x++) for(y=0;y<N;y++) if (wordsearch(w, x, y)) return true; return false; }
Antti huima
source share