当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How would I modify my code to search a multidimensional array diagonally from left to right and right to left?

问题描述:

I have this code for searching a multidimensional array from left to right and right to left.

What I need to do now is to search the array from the top left to the bottom right,the top right to the bottom left, the bottom left to the top right, and the bottom right to the top left.

What would I need to change in my existing methods to make a new method to do what I want?

 // 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

网友答案:

so i assume that your multidimensional array is a cube means row and column has same length.

From top left to bot right compare what you want with board[i][i];

for top right to bot left would be same for loop but compare with board[length-i][i]

for bot left to top right would be compare with board[i][length-i]

for bot right to top left would be compare with board[length-i][length-i]

all of them are in for loop from i to length

分享给朋友:
您可能感兴趣的文章:
随机阅读: