簡體   English   中英

Java單詞匹配的遞歸方法

[英]Java recursive method for word matching

我一直在摸索,試圖弄清楚為什么此遞歸方法與用戶提供的單詞匹配時沒有返回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。 當我調試時,它似乎確實會遍歷數組中的每個位置,但無法識別第一個字符的匹配項並開始檢查第二個字符。 有什么明顯的東西突出嗎?

問題是您缺少正遞歸終止案例。 修改后的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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM