【发布时间】:2025-12-15 07:25:02
【问题描述】:
对于我的家庭作业,我们将使用递归遍历一个虚拟迷宫。我想确保我正在正确读取文件。此时我的代码的目标是读取包含迷宫的文本文件,并在迷宫的起点放置一个“X”。
此外,我在另一篇 SO 帖子上阅读了有关将 BufferedReader 与 FileReader 结合使用的文章,但该帖子有点含糊 - 这样做有什么好处?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class ReadInMaze
{
private static char[][] maze = null;
private static int rows = 0;
private static int cols = 0;
private static int xStart = 0;
private static int yStart = 0;
public static void Maze(File mazeFile) throws IOException
{
File mazeFile = new File ("C:/Users/Mark/workspace/18-20_MazeTraversal_Hard/src/MazeForMazeTraversalHW.txt");
BufferedReader reader = new BufferedReader(new FileReader(mazeFile));
Scanner lineOfFile = new Scanner(reader.readLine());
rows = lineOfFile.nextInt(); //get the number of rows of the maze
cols = lineOfFile.nextInt(); // get the number of columns of the maze
maze = new char[rows][cols]; //create a char array of the proper size
//For loops to iterate the rows and col to find the start/enterance of the maze as it pertains to the first char in the row
for (int y = 0; y < cols; y ++)
{
lineOfFile = new Scanner(reader.readLine());
for(int x = 0; x < rows; x++)
{
char start = lineOfFile.next().charAt(0);
maze[x][y] = start;
//statement to set the starting coorinates for the maze
if (start == '.')
{
xStart = x;
yStart = y;
}
}
}
}
我的文本文件中的迷宫如下所示:
# # # # # # # # # # # #
# . . . # . . . . . . #
. . # . # . # # # # . #
# # # . # . . . . # . #
# . . . . # # # . # . .
# # # # . # . # . # . #
# . . # . # . # . # . #
# # . # . # . # . # . #
# . . . . . . . . # . #
# # # # # # . # # # . #
# . . . . . . # . . . #
# # # # # # # # # # # #
【问题讨论】:
-
就像现在一样,您正在从左上角到右下角查看迷宫中的每个字符,并将每个句点字符的位置保存为开始。这将为您提供最接近底部和右侧的时间段。想想你需要查看哪些行和列才能找到迷宫的入口。
-
你怎么知道从哪里开始?从左边还是右边的起点?
-
不是我的出发点 [0][0] 吗?其中 x = 0 和 y = 0 在嵌套的 for 循环中。这会将我的起点放在网格的左上角吗?
-
是的,那是左上角,但你如何拥有它最后一个'。'通过双 for 循环的将被设置为右侧 '.' 的起点
标签: java recursion bufferedreader filereader traversal