用于单词匹配的Java递归方法

时间:2016-05-18 22:04:20

标签: java android arrays recursion

我一直在撞墙,试图找出为什么这个递归方法在匹配用户提供的单词时没有返回true。

我正在用这个逻辑创建一个2D数组:

charTest = letterString.toCharArray();

    char[][] twoDimCharArray = new char[][] 
            {{charTest[0],charTest[1],charTest[2],charTest[3]},
            {charTest[4],charTest[5],charTest[6],charTest[7]},
            {charTest[8],charTest[9],charTest[10],charTest[11]},
            {charTest[12],charTest[13],charTest[14],charTest[15]}};

用户提供的字符串将传递给以下方法,期望如果它检查2D数组并找到相邻位置的字符串的每个字符,它将从main方法返回true:

public boolean findWord(String word) {
    for (int row = 0; row < this.board2.length; row++) {
        for (int col = 0; col < this.board2.length; col++) {
            if (this.findWord(word, row, col)) {
                return true;
            }
        }
    }
    return false;
}

private boolean findWord(String word, int row, int col) {
   if (    row < 0 || row >= this.board2.length ||
           col < 0 || col >= this.board2.length ||
           this.board2[row][col] != word.charAt(0)) {
        return false;
    }
    else {
        char safe = this.board2[row][col];
        this.board2[row][col] = '*';
        String rest = word.substring(1, word.length());
       Log.v("rest", rest + "");
        boolean result = this.findWord(rest, row-1, col-1) ||
                this.findWord(rest, row-1,   col) ||
                this.findWord(rest, row-1, col+1) ||
                this.findWord(rest,   row, col-1) ||
                this.findWord(rest,   row, col+1) ||
                this.findWord(rest, row+1, col-1) ||
                this.findWord(rest, row+1,   col) ||
                this.findWord(rest, row+1, col+1);
        this.board2[row][col] = safe;
        return result;
    }
}

但是无论字符的位置如何,该方法总是返回false。当我调试时,它似乎确实会遍历数组中的每个位置,但是无法识别第一个字符的匹配并开始检查第二个字符。有什么明显的亮点吗?

1 个答案:

答案 0 :(得分:0)

问题是你错过了一个正面的递归终止案例。修订findWord()

private boolean findWord(String word, int row, int col) {

    if (row < 0 || row >= this.board2.length ||
        col < 0 || col >= this.board2.length ||
        this.board2[row][col] != word.charAt(0)) {
        return false;
    }

    if (word.length() == 1) {
        return true;
    }

    String rest = word.substring(1, word.length());

    char saved = this.board2[row][col];
    this.board2[row][col] = '*';

    boolean result = this.findWord(rest, row-1, col-1) ||
        this.findWord(rest, row-1,   col) ||
        this.findWord(rest, row-1, col+1) ||
        this.findWord(rest,   row, col-1) ||
        this.findWord(rest,   row, col+1) ||
        this.findWord(rest, row+1, col-1) ||
        this.findWord(rest, row+1,   col) ||
        this.findWord(rest, row+1, col+1);

    this.board2[row][col] = saved;

    return result;
}