尝试在java中搜索特定单词的字符网格。从左到右搜索后如何从右到左搜索?

时间:2014-10-07 23:20:55

标签: java search 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 <= 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

1 个答案:

答案 0 :(得分:0)

if ((j+k <= board[i].length) || (letters[k] != board[i][j+k])) {

也需要逆转:

if ((j - k < 0) || (letters[k] != board[i][j-k])) {