如何修改我的代码以从左到右,从右到左对角地搜索多维数组?

时间:2014-10-08 17:25:47

标签: java arrays search matrix multidimensional-array

我有这个代码,用于从左到右,从右到左搜索多维数组。

我现在需要做的是从左上角到右下角搜索阵列,从右上角到左下角,左下角到右上角,右下角到左上角。

我需要在现有方法中做些什么来改变一种新方法来做我想做的事情?

            // Left to Right
            public static String findLeftToRight (char[][]board, String word) {
                char[] letters = word.toCharArray();

                for (int i = 0; i < board.length; i++){
                    for (int j = 0; j < board[i].length; j++) {
                        boolean found = true;

                        for (int k = 0; k < letters.length; k++) {
                            if ((j+k >= board[i].length) || (letters[k] != board[i][j+k])) {
                                found = false;
                                break;
                            }
                        }

                        if (found) {
                            return "String " + word + " found in row=" + i + " col=" +j;
                        }
                    }
                }
                return "String " + word + " not found";
            } // end findLeftToRight

            // Right to Left
            public static String findRightToLeft (char[][]board, String word) {
                char[] letters = word.toCharArray();

                for (int i = board.length-1; i > -1; i--){
                    for (int j = board[i].length-1; j > -1; j--) {
                        boolean found = true;

                        for (int k = 0; k < letters.length; k++) {
                            if ((j - k < 0) || (letters[k] != board[i][j-k])) {
                                found = false;
                                break;
                            }
                        }

                        if (found) {
                            return "String " + word + " found in row=" + i + " col=" +j;
                        }
                    }
                }
                 return "String " + word + " not found";
            } // end findLeftToRight

1 个答案:

答案 0 :(得分:0)

所以我假设您的多维数组是一个多维数据集意味着行和列具有相同的长度。

从左上角到右下角 比较你想要的董事会[i] [i];

左上角的左上角是

循环相同但与board [length-i] [i]

进行比较 机器人左上角的

将是 与董事会[i] [length-i]

进行比较 机器人右上角的

将是 与board [length-i] [length-i]

进行比较

所有这些都是从i到长度的循环