我的任务是编写一个单词搜索求解器。
在这个程序中,用户将决定网格的大小、网格中的字母、要搜索的单词数以及要搜索的单词。
这是我去过的最远的地方。在这里,我计划在输入单词后立即搜索。
#include <stdio.h>
#include <string.h>
int main()
{
int rows, cols; //for the size of grid
int grid_row=0, grid_col=0; // rows/columns of grid
int numsrch; //# of words to look for
printf("Enter grid size: ");
scanf("%d %d", &rows, &cols);
cols+=1; //# of letters per line
char grid[rows][cols]; //array for grid
printf("Enter grid: \n");
for(grid_row=0; grid_row < rows; grid_row++) //where letters in grid are entered
{
scanf("%s", grid[grid_row]);
strlwr(grid[grid_row]);
}
printf("Number of words to look for: ");
scanf("%d", &numsrch);
int gridlookcol=0, gridlookrow=0;
int ltrsrch=0; //to be used later when looking for a letter in the word that's being searched for
char srch[cols]; //array for the word to be looked for
char found[cols]; //array for matched letters
for(grid_row=0; grid_row<numsrch; grid_row++)
{
strcpy(found,"");
ltrsrch=0;
scanf("%s", srch);
strlwr(srch);
for(gridlookrow=0;gridlookrow<rows;gridlookrow++)
{
if(strstr(grid[gridlookrow], srch) || strstr(grid[gridlookrow],strrev(srch)))
{
printf("%s begins at row %d\n", srch, gridlookrow + 1);
break;
}
}
}
return 0;
}
因此,使用上面的代码,我已经成功地将单词水平匹配到右侧。但我还有 7 个方向(上、下、左、右上、左上、左下、右下)。我是否必须为每个方向编写一个 for 循环?