gpt4 book ai didi

java - 矩阵上的递归移动

转载 作者:行者123 更新时间:2023-12-02 01:49:01 26 4
gpt4 key购买 nike

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com