递归(一)


  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
      -----------------
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章