遞歸(一)


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