递归字符串查找

本来想做一道关于BFS或者DFS的OJ上的题,但是网页一直打不开。想起之前曾经看过的在网格中搜索字符串的题,于是自己重新写了一遍。当时看的时候感觉还是有点难度的,但是现在再回过头来自己写一遍,就觉得很简单了。。。




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

#define MAX_HEIGHT  10
#define MAX_WIDTH   10

int  _index_tbl[MAX_HEIGHT+1][MAX_WIDTH+1];
char _test_str[MAX_HEIGHT+1][MAX_WIDTH+1] = 
{
   0,  0 ,  0,   0,   0 ,  0 ,  0,  0,  0 , 0 , 0 ,
   0, 'A', 'C', 'h', 'i', 'l', 'd','H','y','u','w',
   0, 'a', 'b', 'c', 'S', 'D', 'U','H','y','u','w',
   0, 'a', 'p', 'p', 's', 'h', 'u','H','y','u','w',
   0, 'a', 'k', 'l', 'l', 'h', 'u','H','y','u','w',
   0, 'T', 'p', 'p', 's', 'e', 'u','H','y','u','w',
   0, 's', 'E', 'u', 'z', 'h', 'u','H','y','u','w',
   0, 's', 'p', 'S', 's', 'h', 'a','H','y','u','w',
   0, 'a', 'v', 'p', 'T', 'o', 'u','p','y','u','w',
   0, 'a', 'b', 'p', 's', 'h', 'u','H','p','u','w',
   0, 'a', 'n', 'm', 'z', 'h', 'u','H','y','y','w',
};

/* 上,右上,右,右下,下, 左下,左,左上*/
int _dir_x[8] = { -1, -1, 0, 1, 1,  1,  0, -1};
int _dir_y[8] = { 0 ,  1, 1, 1, 0, -1, -1, -1};

/* 保存要查找的字符串 */
char _buffer[255];
/* 找到标志 */
int  _find = 0;

int Dfs(int dir, char *s, int x, int y)
{
    int n = strlen(s);
    if (n == 0)  { return 0; }

    /* 只有首字母正确才继续往下找 */
    if (_test_str[x][y] == *s){
        if (Dfs(dir, s+1, x+_dir_x[dir], y+_dir_y[dir]) == n-1){
            _index_tbl[x][y] = 1;
            return n;
        }else{
            return 0;
        }
    }

    return 0;               
}

void Output(void)
{
    if (!_find){
        printf("can not _find\n");
    }else{
        for (int i = 1; i < 11; ++i){
            for(int j = 1; j < 11; ++j){
                if (_index_tbl[i][j] != 0){
                    printf("%2c", _test_str[i][j]);
                }else{
                    printf("%2c",'.');
                }
            }
            printf("\n");
        }
    }    
}

int main(int argc, char *argv[])
{
    int len;
    while(scanf("%s", _buffer) == 1){
        _find = 0;
        len = strlen(_buffer);
        memset(_index_tbl, 0, sizeof(_index_tbl));
        for (int i = 1; i < 11; ++i){
            for (int j = 1; j < 11; ++j){
                if (_test_str[i][j] == *_buffer){
                    for (int dir = 0; dir < 8; ++dir){
                        if (Dfs(dir, _buffer, i, j) == len){
                            _index_tbl[i][j] = 1;
                            _find = 1;
                            break;
                        }
                    }
                }
                if (_find)  {  break; }
            }
            if (_find)  {  break; }
        }

        Output();
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值