编写一个程序求解字谜游戏问题

题目

编写一个程序求解字谜游戏问题。


思路

借鉴前辈的思路

第一种:对单词表中的每个单词,我们检查每一个有序三元组(行,列,方向),验证是否有单词存在。但坏处是这将导致大量嵌套的for循环。

第二种:对于每一个尚未进行到字谜最后的有序四元组(行,列,方向,字符数)我们可以测试所指的单词是否在单词表中。这也导致使用大量嵌套的for循环。如果在任意单词中的最大字符数已知的情况下,那么该算法有可能节省一些时间。


实现

代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char puzzle[4][4] = {
    {'t','h','i','s'},
    {'w','a','t','s'},
    {'o','a','h','g'},
    {'f','g','g','t'}
};

char *dict[4] = {"this","two","fat","that"};

int wordExist(int x, int y, int dir, int strlen, char *word, int (*position)[2]);

int main(void)
{
    char word[5];
    int position[4][2];
    int x, y, dir, strlen;

    for(x=0;x<4;x++){
        for(y=0;y<4;y++){
            for(dir=0;dir<8;dir++){
                for(strlen=2;strlen<5;strlen++){
                    // 坐标 x y
                    // 方向 dir
                    // 单词长度从2开始
                    if(wordExist(x, y, dir, strlen, word, position) == 1){
                        printf("word: %s\n",word);
                        break;
                    }
                }
            }
        }
    }

    return 0;
}

int wordExist(int x, int y, int dir, int strlen, char *word, int position[][2])
{
    char sword[5];
    int i = 0, j;
    while(i < strlen){
        position[i][0] = x;
        position[i][1] = y;
        sword[i++] = puzzle[x][y];
        sword[i] = '\0';
        for(j=0;j<4;j++){
            if(strcmp(sword,dict[j]) == 0){
                strcpy(word,dict[j]);
                return 1;
            }
        }

        switch (dir){
            case 0:        //从左到右
                y++;
                break;
            case 1:        //从右到左
                y--;
                break;
            case 2:        //从上到下
                x++;
                break;
            case 3:        //从下到上
                x--;
                break;
            case 4:        //从左上到右下
                x++;
                y++;
                break;
            case 5:        //从右下到左上
                x--;
                y--;
                break;
            case 6:        //从左下到右上
                x--;
                y++;
                break;
            case 7:        //从右上到左下
                x++;
                y--;
                break;
            default:
                puts("Direction error.");
                return 0;
         }
         if(x < 0 || y < 0)
            return 0;
    }
    return 0;
}

结果:


原文地址:http://www.cnblogs.com/mingc/p/5861745.html

对其代码有做过一些优化,降低循环次数。
  • 7
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值