gpt4 book ai didi

Java迷宫解决问题

转载 作者:行者123 更新时间:2023-12-01 17:00:40 25 4
gpt4 key购买 nike

所以我被要求解决递归 java 函数中的迷宫,但我偶然发现了一个问题,即递归函数似乎没有将正确的路径切换为“*”。

如有任何帮助,我们将不胜感激。

 public class Maze 
{

/**
* This is only an example,
* you can change this to test other cases but don't forget to submit the work with this main.
* @param args
*/
public static void main(String[] args)
{
int M = 4;
int N = 4;
char[][] maze = {{'1','0','0','0'},{'1','1','0','0'},{'0','1','1','1'},{'0','0','0','1'}};

if (findPath(maze, 0,0))
printMaze(maze);
else
System.out.println("No solution");
}

private static void printMaze(char[][] maze)
{
for (int i = 0; i < maze.length; i++)
{
for (int j = 0; j < maze[0].length; j++)
{
System.out.print(maze[i][j] +" ");
}
System.out.println();
}

}

// you should implement this function
private static boolean findPath(char[][] maze, int i, int j)
{
if ((i+1 > maze.length) || (j+1 > maze[i].length))
return false;
else
{
if (maze[i][j] == 1)
{
maze[i][j] = '*';
if (maze[i+1][j] == 1)
{
return findPath(maze, i+1, j);
}
if (maze[i][j+1] == 1)
{
return findPath(maze, i, j+1);
}
}
}
return true;
}

}

最佳答案

您缺少 1 周围的引号

if (maze[i][j] == 1)

应该是

if (maze[i][j] == '1')

数字 1 和代表数字 1 的字符在 Java(以及任何其他静态类型语言)中是两个不同的东西,因此您无法像这样检查它们是否相等。

我怀疑代码是否会找到所有路径,因为您似乎根本没有向左和向上搜索。

关于Java迷宫解决问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27862755/

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