java - 矩阵上的递归移动

标签 java recursion matrix

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

我的算法: 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


}

最佳答案

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

关于java - 矩阵上的递归移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57440052/

相关文章:

algorithm - 递归函数的 Big-O 表示法

python - Django 查找图中两个顶点之间的路径

c++ - 递归函数错误

matlab - MATLAB 中的向量到矩阵语法

algorithm - 创建一个沿行和列具有常量和的二维二进制矩阵

java - 在 Android 上混合两个文件音频 wav 使用短数组

java - 如何将 'Double for loop(O(n^2))' 变成 'Single for loop(O(n))' ?

python - numpy 数组的 np.max(x ,axis = 1) 和 x.max(axis = 1) 之间的差异

java - 具有多个条件返回的嵌套 if 语句

java - 从 Eclipse 与系统设置环境变量