递归(一)


  n n n n s
  n e e e n
  n e y e n
  n e e e n
  n n n n n

看上面的矩阵,从某一个点开始,任意组合的字符可以组合成某个特定的单词吗?比如从位置(2,2)开始可以组合成单词“yes”吗?
我们需要分析问题需要做的事情,就是比较字符,最终得到一个相同的字符,那我们分解为每次比较一个字符,然后递归下去就可以得到结果。
出口在哪?
1、如果输入的坐标不在区域上,那么失败结束这个分支
2、如果当前首字符不相同,则失败
3、在前两个比较的前提下,如果只有一个字符了,那么返回成功

#include<iostream>
#include<string>

using namespace std;

#define  _X_  5
#define  _Y_  5

int X, Y;
int dx[8] = { -1, -1, -1, 1, 1, 1, 0, 0 };
int dy[8] = { -1, 0, 1, -1, 0, 1, -1, 1 };
char   board[_X_ + 1][_Y_ + 1];
string  word;
//the mat is 5x5
bool isRange(int x, int y){
    return (x >= 0 && x < _X_ && y >= 0 && y < _Y_);
}

bool hasWords(int y, int x, const string& word)
{
    //if the (x,y) is out of range,just stop it
    //
    if (!isRange(x, y))  return false;
    //if the first character is not same,return false
    //
    if (word[0] != board[x][y]) return false;
    //if the length of world is 1,just return true,cause the range and first character compare
    //
    if (word.length() == 1) return true;
    //else just search 8 directions
    //
    for (int dir = 0; dir < 8; dir++){
        int nextX = x + dx[dir];
        int nextY = y + dy[dir];
        if (hasWords(nextY, nextX, word.substr(1))){
            return true;
        }
    }
    //ok,till here,just return false
    return false;
}


int main()
{
    //input the area and start x,y and word,then call the solve function
    //
    for (int i = 0; i < _X_; i++){
        for (int j = 0; j < _Y_; j++){
            cin >> board[i][j];
        }
    }
    cin >> X >> Y>> word;
    if (hasWords(Y, X, word)){
        cout << "ok" << endl;
    }
    else{
        cout << "no" << endl;
    }
    exit(EXIT_SUCCESS);
}

/*
     ------------------
      n n n n s
      n e e e n
      n e y e n
      n e e e n
      n n n n n
      (2,2) yes
      -----------------
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值