简体   繁体   中英

Recursive method that searches an array doesn't work

So I have this recursive method that searches a 4x4 "board" for a word (think boggle except it only looks above, below, left, and right of the current letter). It gets passed an index (the current letter it is searching for from a given word), and the row and column to search around. The first if statement takes care of the first letter, and always works. The next else if statement doesn't work, and I'm not sure why. Any help is appreciated as to why. secondArray is used in another part of the program when it is displayed.

private boolean verifyWord(int index, int row, int column) {
    System.out.println(index + " " + row + " " +column);
    if (index == 0) {
        for (int i = 0; i < letterArray.length; i++) {
            for (int i2 = 0; i2 < letterArray[0].length; i2++) {
                if (letterArray[i][i2] == wordToFind.charAt(index)) {
                    secondArray[i][i2] = true;
                    verifyWord(index+1, i, i2);
                }
            }
        }
    } else if (index > 0 && index < wordToFind.length()) {
        // check above row
        if (row+1 < row) {
            if (letterArray[row+1][column] == wordToFind.charAt(index)) {
                secondArray[row+1][column] = true;
                verifyWord(index+1, row+1, column);
            }
        }

        //check below row
        if (row-1 >= 0) {
            if (letterArray[row-1][column] == wordToFind.charAt(index)) {
                secondArray[row-1][column] = true;
                verifyWord(index+1, row-1, column);
            }
        }

        //check left column
        if (column-1 >= 0) {
            if (letterArray[row][column-1] == wordToFind.charAt(index)) {
                secondArray[row][column-1] = true;
                verifyWord(index+1, row, column-1);
            }
        }

        //check right column
        if (column+1 < letterArray[0].length) {
            if (letterArray[row][column+1] == wordToFind.charAt(index)) {
                secondArray[row][column+1] = true;
                verifyWord(index+1, row, column+1);
            }
        }
    } else {
        boolCheck = true;
    }
    return boolCheck;
}

The first condition if(row+1 < row) in your else if(index > 0 && index < wordToFind.length()) would never be evaluated to true ( x+1 is always bigger than x ).

You probably want it to be if(row+1 < letterArray.length)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM