[英]I am trying to search my java multidimensional array from bottom right to top left going in a vertical pattern? What is wrong with my code?
[英]How would I modify my code to search a multidimensional array diagonally from left to right and right to left?
我有這段代碼,用於從左到右和從右到左搜索多維數組。
我現在需要做的是從左上到右下,從右上到左下,從左下到右上,從右下到左上搜索數組。
我需要在現有方法中進行哪些更改以使新方法能夠執行我想要的工作?
// 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
所以我認為您的多維數組是一個多維數據集,意味着行和列的長度相同。
從左上方到機器人右側,將您想要的內容與board [i] [i];
機器人左上角的右上角對於循環來說是相同的,但與board [length-i] [i]比較
從左至右的漫游器將與board [i] [length-i]比較
機器人從右上方到左上方將與board [length-i] [length-i]比較
他們全都在從i到length的for循環中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.