我有一个程序应该在单词搜索谜题中搜索“ruby”、“python”和“java”。我的教授给了我从左到右搜索的代码,但我不确定如何从右到左和对角线搜索。我见过其他人编写同样的问题,但我认为我的教授希望我用她做过的类似方法来做。
我试图从右到左,但我要么得到一个超出范围的异常,要么搜索结果为负。
public static void main (String[] argv)
{
char[][] puzzle = {
{'n', 'o', 'h', 't', 'y', 'p', 's'},
{'m', 'i', 'a', 'r', 'y', 'c', 'c'},
{'l', 'l', 'e', 'k', 's', 'a', 'h'},
{'r', 'u', 'b', 'y', 'v', 'm', 'e'},
{'e', 'h', 'h', 'a', 'l', 'l', 'm'},
{'p', 'c', 'j', 'n', 'i', 'c', 'e'},
{'r', 'e', 'e', 'k', 'b', 'i', 'p'}
};
String result1 = findWordLefttoRight (puzzle, "ruby");
String result2 = findWordRighttoLeft (puzzle, "python");
//String result3 = findWordBottomLefttoTopRight (puzzle, "java");
System.out.println (result1);
System.out.println (result2);
//System.out.println (result3);
}
/*Given by Professor*/
static String findWordLefttoRight (char[][] puzzle, String word)
{
// First convert the String into a char array.
char[] letters = word.toCharArray ();
// Now try every possible starting point in the puzzle array.
for (int i=0; i<puzzle.length; i++) {
for (int j=0; j<puzzle[i].length; j++) {
// Use (i,j) as the starting point.
boolean found = true;
// Try to find the given word's letters.
for (int k=0; k<letters.length; k++) {
if ( (j+k >= puzzle[i].length) || (letters[k] != puzzle[i][j+k]) ) {
// Not a match.
found = false;
break;
}
}
// If we went the whole length of the word, we found it.
if (found) {
return "String " + word + " found in row=" + i + " col=" +j;
}
}
}
return "String " + word + " not found";
}
/* My attempt at going from right to left */
static String findWordRighttoLeft (char[][] puzzle, String word)
{
// First convert the String into a char array.
char[] letters = word.toCharArray ();
// Now try every possible starting point in the puzzle array.
for (int i=puzzle.length; i>0; i--) {
for (int j=puzzle.length; j>0; j--) {
// Use (i,j) as the starting point.
boolean found = true;
// Try to find the given word's letters.
for (int k=0; k<letters.length; k++) {
if ( (j+k <= puzzle.length) || (letters[k] == puzzle[i][j+k]) ) {
// Not a match.
found = false;
break;
}
}
// If we went the whole length of the word, we found it.
if (found) {
return "String " + word + " found in row=" + i + " col=" +j;
}
}
}
return "String " + word + " not found";
}