java - 使用二维数组导航 .txt 文件

标签 java arrays character-arrays

对于这个作业,我将读取一个 .txt 文件并递归地导航它产生的迷宫(我将在下面提供一个示例)导航并打印它。我已经放下了导航,我的伙伴正在制作打印方法。但是,我在确定迷宫的起始位置时遇到问题。在迷宫中,起点用 s 表示。用图片更容易解释,所以我现在提供

5    
#####
#s.##
##..#
###.#
#g..#

顶部的数字决定了数组的大小(我们必须将它们设为正方形)。 “#”是一堵墙,“.”是一堵墙。是可用路径,“g”是目标。现在我的问题是找到 s 的坐标,以便我知道从哪里开始迷宫。下面将是文件选择器类(问题所在)和导航迷宫的类(它可以工作,但我想我会包含它,以防有人好奇

public static void main(String[] args)
    throws FileNotFoundException, IOException
    {
        FileReader myReader;
        JFileChooser chooser = new JFileChooser();
        if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
        {
            File myFile = chooser.getSelectedFile();
            myReader = new FileReader(myFile);   
            Scanner myScanner = new Scanner(myReader);
            String placeHolder = myScanner.nextLine();
            int arrayThings = Integer.parseInt(placeHolder);
            char[][] maze = new char[arrayThings][arrayThings];
            int rows = 0;
            int collumns = 0;
            for(int i = 0; i < maze.length(); i++)
            {
                if (maze[rows][collumns] == 's' || maze[rows][collumns] =='S')
                {
                    FindPath(maze[arrayThings][arrayThings],rows,collumns);
                }                    
            }               
            myReader.close();
        }           
    }

我不完全确定如何在迷宫中找到“s”。现在这是 FindPath 方法

public static boolean FindPath(char[][] maze,int x,int y)
    {
        try
        {
            if (maze[x][y] == 'g' || maze[x][y] =='G')
            {
                System.out.println("The maze was printed");  //Replace with print method
                return true;
            }
            else if (maze[x][y] == '#' || maze[x][y] == '?' || maze[x][y] == 'P')
                return false;
            else 
            {
                maze[x][y] = 'P';
                System.out.println("The maze was printed"); //Replace with print method
                if(MazeSolver.FindPath(maze,x,y-1)== true)
                    return true;
                else if(MazeSolver.FindPath(maze,x+1,y)== true)
                    return true;
                else if(MazeSolver.FindPath(maze,x,y+1)== true)
                    return true;
                else if(MazeSolver.FindPath(maze,x-1,y)== true)
                    return true;
                maze[x][y] = '?';
                return false;
            }
        } 
        catch (ArrayIndexOutOfBoundsException myEx)
        {
            return false;
        }        
    }

最佳答案

有两件事需要注意:

第一
下面的代码在二维数组被填充后,在二维数组中搜索字符s

for(int row = 0; row < maze.length; row++)
{
    for(int col = 0; col < maze[0].length;col++){
        if(maze[row][col] == 's'){
            System.out.println("x :" + row + " y : " + col);
        }
    }
}

为什么在填充二维数组时不查找并跟踪字符s?这将使您不必再次迭代二维数组。

row = 0;
maze = new char[arraySize][arraySize];
while(input.hasNextLine()) {
    String lineHolder = input.nextLine();
    // get the char array from the String
    maze[row] = lineHolder.toCharArray();
    if(lineHolder.indexOf('s') != -1) {
        // start row equals the current row
        sRow = row;
        // start column equals the index/column of 's'
        sCol = lineHolder.indexOf('s');
    }
    row = row + 1;
}

第二
无需使用 try catch block 来连接递归,只需实现边界检查即可。

// maze bounds checking, recursion no longer hinges on an exception
// being thrown
if(y < 0 || x < 0 || y > maze.length-1 || x > maze[0].length-1) {
    return false;
}
<小时/>

我添加了以下工作代码来为上面提供的信息提供上下文。

工作代码

public static void main(String[] args) {
    JFileChooser chooser = null;
    Scanner input = null;
    int arraySize = 0;
    char[][] maze;
    int row = 0;
    int sRow = 0;
    int sCol = 0;

    chooser = new JFileChooser();

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        try {
            input = new Scanner(chooser.getSelectedFile());
        } catch(Exception e) {
            System.out.println(e.getLocalizedMessage());
        }
    } else {
        System.out.println("Exiting...");
        System.exit(0);
    }

    if(input.hasNextLine()) {
        arraySize = Integer.parseInt(input.nextLine().trim());
    }

    row = 0;
    maze = new char[arraySize][arraySize];
    while(input.hasNextLine()) {
        String lineHolder = input.nextLine();
        // get the char array from the String
        maze[row] = lineHolder.toCharArray();
        if(lineHolder.indexOf('s') != -1) {
            // start row equals the current row
            sRow = row;
            // start column equals the index/column of 's'
            sCol = lineHolder.indexOf('s');
        }
        row = row + 1;
    }
    input.close();

    System.out.println("The maze has been read in:");
    printMaze(maze);

    FindPath(maze, sCol, sRow);
}

public static boolean FindPath(char[][] maze, int x, int y) {
    // maze bounds checking, recursion no longer hinges on an exception
    // being thrown
    if(y < 0 || x < 0 || y > maze.length-1 || x > maze[0].length-1) {
        return false;
    }

    if (Character.toLowerCase(maze[x][y]) == 'g') {
        System.out.println("The maze has been solved:");
        maze[x][y] = 'P';
        printMaze(maze);
        return true;
    }

    if(maze[x][y] == '.' || maze[x][y] == 's') {
        maze[x][y] = 'P';
        System.out.println("Solving...");
        printMaze(maze);

        if (FindPath(maze, x, y - 1)) {
            return true;
        } else if (FindPath(maze, x + 1, y)) {
            return true;
        } else if (FindPath(maze, x, y + 1)) {
            return true;
        } else if (FindPath(maze, x - 1, y)) {
            return true;
        }

        return true;
    } else {
        // if maze[x][y] equals # or P then return false
        return false;
    }
}

public static void printMaze(char[][] maze) {
    for(int r = 0; r < maze.length; r++) {
        for(int c = 0; c < maze[r].length; c++) {
            System.out.print(maze[r][c]);
        }
        System.out.print("\n");
    }
}

输出

The maze has been read in:
#####
#s.##
##..#
###.#
#g..#
Solving...
#####
#P.##
##..#
###.#
#g..#
Solving...
#####
#PP##
##..#
###.#
#g..#
Solving...
#####
#PP##
##P.#
###.#
#g..#
Solving...
#####
#PP##
##PP#
###.#
#g..#
Solving...
#####
#PP##
##PP#
###P#
#g..#
Solving...
#####
#PP##
##PP#
###P#
#g.P#
Solving...
#####
#PP##
##PP#
###P#
#gPP#
The maze has been solved:
#####
#PP##
##PP#
###P#
#PPP#

关于java - 使用二维数组导航 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29378475/

相关文章:

java - GWT I18N - 显示列表中的字符串

java - 如何在Java应用程序中使用scala类JavaDStreamKafkaWriter?

java - 如何改变 while(true)

java - 深入比较数组中的每个元素

C: 为什么数组的元素需要通过内存地址扫描?

java - 这种对象的使用是否多余和/或效率低下?

java - Java 中的对象文字

c - 与**字符**一起使用时作为参数的数组 VS 与**整数**一起使用时

c - 如何在 C 中使用 baskspace 从字符串中删除一个字符?

C++ 将字符数组转换为大写(无 MFC)