题目
编写一个程序求解字谜游戏问题。
思路
借鉴前辈的思路
第一种:对单词表中的每个单词,我们检查每一个有序三元组(行,列,方向),验证是否有单词存在。但坏处是这将导致大量嵌套的for循环。
第二种:对于每一个尚未进行到字谜最后的有序四元组(行,列,方向,字符数)我们可以测试所指的单词是否在单词表中。这也导致使用大量嵌套的for循环。如果在任意单词中的最大字符数已知的情况下,那么该算法有可能节省一些时间。
实现代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define DICTSIZE 4 //字典内最大单词数
#define WORDSIZE 21 //单词最大长度 + 1
char puzzle[4][4] =
{
{ 't', 'h', 'i', 's' },
{ 'w', 'a', 't', 's' },
{ 'o', 'a', 'h', 'g' },
{ 'f', 'g', 'g', 't' }
}; //字谜
char * dict[DICTSIZE] = { "this", "two", "fat", "that" }; //字典
bool wordExist( int x, int y, int dir, int len, char * word )
{
char str[WORDSIZE];
int cnt = 0;
for( int i=0; i<len; i++ )
{
str[cnt] = puzzle[x][y];
str[cnt + 1] = '\0';
for( int j=0; j<DICTSIZE; j++ ) //遍历查找匹配
{
if(!strcmp(str,dict[j]))
{
strcpy(word,str);
return true;
}
}
cnt++;
switch(dir)
{
case 0: y--;break; //往左
case 1: x--,y--;break; //往左上
case 2: x--;break; //往上
case 3: x--,y++;break; //右上
case 4: y++;break; //往右
case 5: x++,y++;break; //右下
case 6: x++;break; //下
case 7: x++,y--;break; //左下
default: printf("position error!");return false;
}
}
return false;
}
int main()
{
char word[WORDSIZE];
for( int row=0; row<4; row++ )
{
for( int col=0; col<4; col++ )
{
for( int d=0; d<8; d++ )
{
for( int len = 1; len<=4; len++ )
{
if( wordExist(row,col,d,len,word) )
{
printf("%s\n",word);
break;
}
}
}
}
}
return 0;
}