【问题标题】:Recursive movement on matrix矩阵上的递归移动
【发布时间】:2019-08-10 06:57:49
【问题描述】:

我正在尝试编写一个递归函数来检查字符串矩阵中所有可能的路径以构建一个单词,我只能向上、向下、向右和向左移动。 该功能不起作用,我不明白为什么..

我的算法: 1. 如果下一步有效: 1.1 在字符串中添加下一个字母 1.2 检查单元格为“已访问”(Stepped) 1.3 如果字符串是一个单词,打印它。 2. 对下一步的所有选项执行相同操作:右、左、上和下。

// Function to check if it is possible to go to position next
// from current position. The function returns false if next is
// not a valid position or it is already visited
public static boolean isValid(int x, int y, boolean[][] isStepped)
{
    int M = 4;
    int N = 4;
    return (x >= 0) && (x < M) &&
            (y >= 0) && (y < N) &&
            (!isStepped[x][y]);
}
public static void printWords(String A[][], int next_x, int next_j, boolean[][] isStepped, String s)
{
    if (isValid(next_x,next_j, isStepped)) // check if next step in bounds of array and not stepped already
    {
        s+=A[next_x][next_j]; // Add the valid letter to s
        isStepped[next_x][next_j] = true;
        if(isWord(s)) // check if the letters until now Constitute a word
        {
            System.out.println(s + " ");
        }
    }
    printWords(A, next_x+1, next_j, isStepped, s); // Move Up
    printWords(A, next_x-1, next_j, isStepped, s); // Move Down
    printWords(A, next_x, next_j+1, isStepped, s); // Move Right
    printWords(A, next_x, next_j-1, isStepped, s); // Move Left


}

【问题讨论】:

    标签: java recursion matrix


    【解决方案1】:

    您永远不会将字段重置为“false”以使其可用于下一次搜索。一个字段一旦被使用,就再也不能使用了。

    【讨论】:

      猜你喜欢
      • 2019-11-13
      • 2018-03-29
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      相关资源
      最近更新 更多