递归字符串查找

来源:互联网 发布:网络发彩信 编辑:程序博客网 时间:2024/06/10 07:28

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




#include <stdlib.h>#include <stdio.h>#include <string.h>#define MAX_HEIGHT  10#define MAX_WIDTH   10int  _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
原创粉丝点击