在Java中递归搜索

时间:2011-04-23 15:54:08

标签: java search recursion depth-first-search

所以我一直在为游戏摇篮编写一个程序。我创建了一个供用户使用的小板,但问题是我不知道如何以递归方式检查该字是否在板上。我希望能够检查输入的单词是否确实在板上,并且是有效的。我的意思是,这个词的字母必须彼此相邻。对于那些玩过傻瓜的人来说,你会明白我的意思。我想做的就是检查这个词是否在板上。

这就是我到目前为止所做的......

import java.io.*;
public class boggle {
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    private String s = "";
    private int [][] lettersNum = new int [5][5];
    private char [][] letters = new char [5][5];
    private char [] word = new char [45]; // Size at 45, because the longest word in the dictionary is only 45 letters long 
    private char [] temp; 

    public void generateNum()
    {
        for (int row = 0; row < 5; row ++)
        {
            for (int col = 0; col < 5; col++)
            {
                lettersNum [row][col] = (int) (Math.random() * 26 + 65);
            }
        }
    }

    public void numToChar()
    {
        for (int row = 0; row < 5; row ++)
        {
            for (int col = 0; col < 5; col++)
            {
                letters [row][col] = (char)(lettersNum[row][col]);
            }
        }
    }

    public void display()
    {
        for (int row = 0; row < 5; row ++)
        {
            for (int col = 0; col < 5; col++)
            {
                System.out.print(letters[row][col]);
            }
            System.out.println("");
        }
    }

    public void getInput() throws IOException
    {
        System.out.println("Please enter a word : ");
        s=br.readLine();
        s=s.toUpperCase();
        word = s.toCharArray();
    }

    public int search(int row, int col)
    {
        if((row <0) || (row >= 5) || (col < 0) || (col >= 5))
        {
            return (0);
        }
        else
        {
            temp = word;
            return (1+ search(row +1, col) +
                    search(row -1, col) + 
                    search(row, col + 1) + 
                    search(row, col-1) +
                    search(row +1, col +1)+
                    search(row +1, col -1)+
                    search(row -1, col +1)+
                    search(row -1, col -1));
        }
    }


}

搜索是我的搜索算法,以检查该字是否在板上,但我不知道它是否正确或是否可行。此外,我不知道如何实际告诉用户该单词是有效的!

感谢所有帮助:)

所以我尝试使用你在下面提出的建议,但我真的不理解int [5] [5]的事情。所以这就是我的尝试,但我不断出错!这是悲伤......

    public void locate()
{
    temp = word[0];
    for (int row = 0; row <5; row++)
    {
        for (int col = 0; col <5; col++)
        {
            if(temp == letters[row][col])
            {
                search(row,col);
            }
        }
    }
}

public int search(int row, int col)
{
    if(letters[row][col-1]==word[count]) // Checks the letter to the left
    {
        count++;
        letters[row][col-1] = '-'; // Just to make sure the program doesn't go back on itself
        return search(row, col-1);
    }
    else if (letters[row][col+1] == word[count])// Checks the letter to the right
    {
        count++;
        letters[row][col+1] = '-';// Just to make sure the program doesn't go back on itself
        return search(row, col +1);
    }
    else if (letters[row+1][col]== word[count])// Checks the letter below
    {
        count++;
        letters[row+1][col] = '-';// Just to make sure the program doesn't go back on itself
        return search(row +1 , col);
    }
    else if (letters[row-1][col]== word[count])// Checks the letter above 
    {
        count++;
        letters[row-1][col] = '-';// Just to make sure the program doesn't go back on itself
        return search(row -1 , col);
    }
    else if (letters[row-1][col-1]== word[count])// Checks the letter to the top left
    {
        count++;
        letters[row-1][col-1] = '-';// Just to make sure the program doesn't go back on itself
        return search(row -1 , col-1);
    }
    else if (letters[row-1][col+1]== word[count])// Checks the letter to the top right
    {
        count++;
        letters[row-1][col+1] = '-';// Just to make sure the program doesn't go back on itself
        return search(row -1 , col+1);
    }
    else if (letters[row+1][col-1]== word[count])// Checks the letter to the bottom left
    {
        count++;
        letters[row+1][col-1] = '-';// Just to make sure the program doesn't go back on itself
        return search(row +1 , col-1);
    }
    else if (letters[row+1][col+1]== word[count])// Checks the letter to the bottom right
    {
        count++;
        letters[row+1][col+1] = '-';// Just to make sure the program doesn't go back on itself
        return search(row +1 , col+1);
    }
    return 0;
}

private int count = 0; (被宣布为班级的最高层,以防你想知道我从哪里得到了[count]来自

1 个答案:

答案 0 :(得分:3)

您当前的搜索功能实际上并没有做任何事情。我假设这是家庭作业所以,没有免费的午餐;)

最简单的方法是使用两个递归函数:

public boolean findStart(String word, int x, int y)

这将对电路板进行线性搜索,寻找word中的第一个字符。如果您当前的位置不匹配,请使用下一组坐标自称。当找到匹配项时,它会使用word,当前位置和新的空4x4矩阵调用第二个递归函数:

public boolean findWord(String word, int x, int y, int[][] visited)

此函数首先检查当前位置是否与word中的第一个字母匹配。如果是,则会在visited中标记当前位置并循环显示所有相邻的正方形,除了visited 中标记的那些,通过调用word.substring(1)和那些坐标。如果word中的字母用完,您就找到了它并返回true。请注意,如果您返回false,则需要从visited删除当前位置。

可以使用一个功能执行此操作,但通过拆分逻辑,我个人认为在您脑海中管理变得更容易。一个缺点是它确实对一个单词中的每个第一个字母进行了额外的比较。要使用单个函数,您需要使用布尔值或深度计数器跟踪您所处的“模式”。

修改:您最长的字词应为16。 Boggle使用4x4板,一个单词不能使用相同的位置两次。并不是说这真的很重要,但它可能用于任务。另请注意,我刚刚在脑海中做到这一点并且不知道我100%正确 - 评论赞赏。

根据评论进行修改:

使用上面概述的方法,您的迭代locate就是这样:

public boolean locate(String word) 
{ 
    for (int row = 0; row < 4; row++) 
    {  
        for (int col =0; col < 4; col++) 
        { 
            if (word.charAt(0) == letters[row][col])
            {
                boolean found = findWord(word, row, col, new boolean[4][4]);
                if (found) 
                    return true;
            } 
        } 
     }
     return false;
}    

同样的事情递归看起来如下,这应该有所帮助:

public boolean findStart(String word, int x, int y)
{
    boolean found = false;
    if (word.charAt(0) == letters[x][y])
    {
        found = findWord(word, x, y, new boolean[4][4]);
    } 

    if (found)
        return true;
    else 
    {
        y++;
        if (y > 3)
        {
            y = 0;
            x++;
        }

        if (x > 3)
           return false;    
    }

    return findStart(word, x, y);
}        

所以这里是findWord()和帮助方法getAdjoining(),向您展示这一切是如何运作的。请注意,我将visited数组更改为boolean只是因为它有意义:

public boolean findWord(String word, int x, int y, boolean[][] visited)
{
    if (letters[x][y] == word.charAt(0))
    {
        if (word.length() == 1) // this is the last character in the word
            return true;
        else
        {
            visited[x][y] = true;
            List<Point> adjoining = getAdjoining(x,y,visited);

            for (Point p : adjoining)
            {
                boolean found = findWord(word.substring(1), p.x, p.y, visited);
                if (found)
                    return true;
            }
            visited[x][y] = false;
        }

    }
    return false;
}

public List<Point> getAdjoining(int x, int y, boolean[][] visited)
{
    List<Point> adjoining = new LinkedList<Point>();

    for (int x2 = x-1; x2 <= x+1; x2++)
    {
        for (int y2 = y-1; y2 <= y+1; y2++)
        {
            if (x2 < 0 || x2 > 3 ||
                y2 < 0 || y2 > 3 ||
                (x2 == x && y2 == y) ||
                visited[x2][y2])
            {
                continue;
            }

            adjoining.add(new Point(x2,y2));

        }
    }

    return adjoining;
}

现在,在您从用户那里获得String(单词)的输入后,您只需致电:

boolean isOnBoard = findStart(word,0,0);

我最初是在脑子里做到这一点,然后沿着那条路去尝试告诉你它是如何工作的。如果我要实际实现这一点,我会做一些不同的事情(主要是消除单词中第一个字母的双重比较,可能是将两者合并为一种方法,尽管你可以通过重新安排当前方法中的逻辑来实现),但上面的代码确实起作用,应该可以帮助您更好地理解递归搜索。