[英]Recursive array search of char array
我試圖弄清楚如何以遞歸方式搜索一個字符數組的單詞,並返回是否存在。 可以將它想像成單詞搜索的編程等效項。 我當前的代碼如下。 9999的種子值有助於測試。 如何編寫遞歸搜索方法以驗證char數組中是否存在給定單詞?
public class Board {
private char[][] board = new char[4][4];
private boolean[][] visited = new boolean[4][4];
private String word;
public Board(int seed){
word = "";
Random rand = new Random(seed);
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
char randomChar = (char) (rand.nextInt(27) + 65);
//System.out.print(" " + randomChar + " ");
board[i][j] = randomChar;
//System.out.print(board[i][j]);
}//System.out.println();
}
}
public void resetBoard(){
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
visited[i][j] = false;
}
}
}
public void printBoard(){
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(j == 0)
System.out.println("+---+ +---+ +---+ +---+");
System.out.print("| " + board[i][j] + " | ");
}
System.out.println("\n+---+ +---+ +---+ +---+");
}
}
public boolean verifyWord(String w){
this.word = w;
for(int i = 0; i < w.length(); i++){
// char letter = w.charAt(i);
// System.out.println(letter);
boolean wordVerify = verifyWordRecursively(0, 0, 0);
if(wordVerify == true)
return true;
// if(i == w.length() - 1){
// if(wordVerify == true)
// return true;
// }
}return false;
}
public boolean verifyWordRecursively(int wordIndex, int row, int col){
char letter = word.charAt(wordIndex);
System.out.println(letter);
if(board[row][col] == letter){
return true;
}
else{
if(col + 1 < board[0].length){
verifyWordRecursively(wordIndex, row, col + 1);
}
if(row + 1 < board.length){
verifyWordRecursively(wordIndex, row + 1, col);
}
}return false;
}
}
這是我的主要課程:
public class LA2Main {
public static void main(String[] args) throws IOException{
int seed = getSeed();
Board b = new Board(seed);
b.printBoard();
Scanner inFile = new Scanner(new FileReader("input.txt"));
// while(inFile.hasNextLine()){
// System.out.println(inFile.nextLine());
String word = inFile.nextLine();
b.resetBoard();
System.out.println("-----------------------\n" + word);
boolean isVerified = b.verifyWord(word);
if(isVerified == true)
System.out.println("'" + word + "' was found on the board!");
else
System.out.println("'" + word + "' is NOT on this board");
b.printBoard();
// }
}
public static int getSeed(){
Scanner sc = new Scanner(System.in);
int userInput;
while(true){
try{
System.out.println("Enter an integer seed value greater than 0: ");
userInput = Integer.parseInt(sc.next());
if( userInput > 0)
return userInput;
}
catch(NumberFormatException e){
System.out.println("Invalid!");
}
}
}
}
在char數組中查找單詞的最簡單方法可能是先將其轉換為String
,然后再使用contains
,而無需重新發明輪子:
boolean contains = new String(myCharArray).contains(myWord);
這是case sensitive
最基本方法 ,如果該單詞只是較大單詞的子部分,則返回true
,因此更合適的方法是將matches
與不區分大小寫的正則表達式配合使用,該正則表達式定義了單詞邊界,如下所示:
boolean contains = new String(myCharArray).matches(
String.format("(?i)^.*\\b%s\\b.*$", Pattern.quote(myWord))
);
所以我想這個問題是針對遞歸字符串匹配的,盡管前面已經指出了這可能不是最好的方法,但仍然可以使用它。
查看您的代碼,您不想與char數組匹配,而是要與char矩陣匹配。 讓我們采用幼稚的方法,因為無論如何我們都處於低效的道路上。
我將提供一些偽代碼,讓我們從一些代碼開始,這些代碼檢查矩陣是否在某個偏移量處與數組匹配:
function matches(char matrix[][], char needle[], int row, int col)
width, height = dimensions(matrix)
/* Check whether we're out of range */
if (width * height < row * width + col + length(needle)) {
return false
}
for (int i = 0 ... len(needle)) {
if (matrix[row][col] != needle[i]) {
return false
}
/* increment position, (hint: integer division) */
row += (col + 1) / width
col = (col + 1) % width
}
return true
現在,這仍然不是遞歸解決方案,並且該函數具有很多參數(對於代碼清晰性而言不是很好)。 讓我們先寫一個包裝器:
function matches(char matrix[][], char needle[])
recursiveMatches(matrix, needle, 0, 0)
recursiveMatches必須跟蹤其原始行和列,以進行適當的遞歸調用。 當然,它需要遞歸調用才能在以下位置失敗:
function recursiveMatches(char matrix[][], char needle[], int row, int col)
width, height = dimensions(matrix)
originalRow, originalCol = row, col
/* Check whether we're out of range */
if (width * height < row * width + col + length(needle)) {
return false
}
for (int i = 0 ... len(needle)) {
if (matrix[row][col] != needle[i]) {
/* add one to the position */
originalRow += (originalCol + 1) / width
originalCol = (originalCol + 1) % width
return recursiveMatches(matrix, needle, originalRow, originalCol)
}
/* increment position */
row += (col + 1) / width
col = (col + 1) % width
}
return true
我希望將其轉換為適當的Java代碼應該不會太困難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.