我尝试将网格存储在char 的二维数组中,因为需要担心的边界条件更少(例如char * 指向不同长度的字符串)。无论如何,这是结果。本例中使用的网格是从Types of Dog Word Search“借来的”。
#include <stdio.h>
#include <string.h>
static void findword(const char *word, const char *grid, int rows, int cols)
{
int len = strlen(word);
int xdir, ydir, xstart, ystart, xend, yend, xpos, ypos, pos, step, i;
for (xdir = -1; xdir <= 1; xdir++) {
xstart = xdir < 0 ? len - 1 : 0;
xend = xdir > 0 ? cols - len : cols - 1;
if (xend < xstart)
continue;
for (ydir = -1; ydir <= 1; ydir++) {
if (ydir == 0 && xdir == 0)
continue;
ystart = ydir < 0 ? len - 1 : 0;
yend = ydir > 0 ? rows - len : rows -1;
if (yend < ystart)
continue;
for (xpos = xstart; xpos <= xend; xpos++) {
for (ypos = ystart; ypos <= yend; ypos++) {
pos = ypos * cols + xpos;
step = ydir * cols + xdir;
for (i = 0; i < len; i++) {
if (word[i] != grid[pos])
break;
pos += step;
}
if (i == len) {
printf("Found %s at row %d, column %d, dir %s%s\n",
word, ypos + 1, xpos + 1,
ydir < 0 ? "north" : ydir > 0 ? "south" : "",
xdir < 0 ? "west" : xdir > 0 ? "east" : "");
}
}
}
}
}
}
#define GRID_COLS 14
#define GRID_ROWS (sizeof(wordgrid) / sizeof(wordgrid[0]))
static const char wordgrid[][GRID_COLS] = {
"ESULBULLDOGHER",
"EDHISHLSRUDSRE",
"IARELIEWTTORRE",
"RLGTLAEITCORGI",
"EMRDERIISLEPCF",
"HARSCANHHHLEHF",
"CTREDOETOEGBII",
"SIETLPLUHEATHT",
"NAITHXNLAUECUS",
"INRELDEEIBBOAA",
"PNRREOADREHGHM",
"UDEAAERHIAFRUI",
"BRTOBOXERHTSAI",
"LELAMSLRLHUDRL"
};
#define NUM_WORDS (sizeof(words) / sizeof(words[0]))
static const char * const words[] = {
"CHIHUAHUA", "BULLDOG", "TERRIER", "COLLIE", "SHEPHERD", "BOXER",
"HOUND", "BEAGLE", "CORGI", "ROTTWEILER", "PINSCHER", "DALMATIAN",
"SETTER", "MASTIFF"
};
int main(void)
{
int i;
printf("Grid:\n\n");
for (i = 0; i < GRID_ROWS; i++)
printf("%.*s\n", GRID_COLS, wordgrid[i]);
printf("\n");
for (i = 0; i < NUM_WORDS; i++) {
printf("*** Looking for %s ***\n", words[i]);
findword(words[i], &wordgrid[0][0], GRID_ROWS, GRID_COLS);
}
return 0;
}
可能有更有效的算法,例如在网格中搜索单词的第一个字母,然后检查八个方向以查找单词的其余字母(根据网格位置和单词长度过滤掉不可能的方向)。