我试图从垂直模式中从右下角到左上角搜索我的java多维数组?我的代码出了什么问题?

时间:2014-10-09 15:43:50

标签: java search multidimensional-array

我正在尝试从右下角到左上角搜索我的java多维数组,以查找垂直模式中的单词,但它找不到该单词。我做错了什么?

      public static String findBottomToTop(char[][] board, String word) {
        char[] letters = word.toCharArray();

        if (letters.length <= board.length) {
            int lettersIndex = 0;

            for (int i = board.length-1; i > -1; i--) {

                for (int j = board[i].length-1; j > -1; j--) {
                    if (board[i][j] == letters[0]) {
                        lettersIndex++;

                        for (int k = 0; k < letters.length; k++) {
                            if (j > board[k].length && board[k][j] == letters[lettersIndex]) {
                                lettersIndex++;

                                if (lettersIndex == letters.length) {
                                    return "String " + word + " found in row=" + i + " col=" + j;
                                }
                            } else {
                                // breaks
                                lettersIndex = 0;
                                break;
                            }
                        }
                    }// found first
                }
            }
        }
        return "String " + word + " not found";
    }

1 个答案:

答案 0 :(得分:1)

您需要切换

   for (int i = board[0].length-1; i > -1; i--) {

       for (int j = board.length-1; j > -1; j--) {

你想在最右边的角落环绕行,然后向左移动并做同样的事情。只需改变循环的逻辑。