摘要:(1)输入由一些单词和字母的二维数组组成。目标是找出字谜中的单词。这些单词可能以竖直,水平,或者斜上斜下(共8个方向)放置。
(2)在这里,采用一个最基本的,也是最低效率的算法(后面会再次回到这个问题),那就是对每一个字母从8个方向进行搜索,并且与给定的单词进行匹配。算法效率是RCW(行,列,单词数量)
实例:
#include "stdafx.h"
#include "time.h"
#include<stdlib.h>
#include <string.h>
#define Left 1
#define Right 2
#define Up 3
#define Down 4
#define Left_Up 5
#define Right_Down 6
#define Left_Down 7
#define Right_Up 8
void find(int x_init,int y_init,char *test, char S[][4])
{
int direction[8] = {Left,Right,Up, Down, Left_Up,Right_Down,Left_Down,Right_Up};
for (int i =0;i<=7;i++)
{
int x = x_init;
int y = y_init;
int j = 0;//控制单词的字符
while(1)
{
if(test[j] == S[x][y] )
{
switch(direction[i])
{
case Left:
y--;
break;
case Right:
y++;
break;
case Up:
x--;
break;
case Down:
x++;
break;
case Left_Up:
y--;
x--;
break;
case Right_Down:
x++;
y++;
break;
case Left_Down:
y--;
x++;
break;
case Right_Up:
y++;
x--;
break;
}//switch
j++;//字符前进一步
if (!(x<=3&&x>=0&&y<=3&&y>=0))
break;//该方向已到尽头
}
else
break;
}// 该方向字符走完
if (test[j] ==test[19])
{
printf("%s has been found\n",test);
}
}// 换一个方向
return;
}
int _tmain(int argc, _TCHAR* argv[])
{
clock_t start,finish;
start = clock();
char test[20] = {0};
char *p[] = {"this","two","fat","that","oai","tdg"};
char S[][4] ={'t','h','i','s','w','a','t','s','o','a','h','g','f','g','d','t'};
for(int m = 0;m<=5;m++)
{
memset(test,0,sizeof(test));
memcpy(test,p[m],10*sizeof(char));
for (int i = 0;i<=3;i++)
{
for (int j = 0;j<=3;j++)
{
if (test[0] == S[i][j])
find(i,j,test,S);
}
}
}
finish = clock();
printf("The process use %f seconds", (double)(finish - start)/CLOCKS_PER_SEC);
system("pause");
return 0;