Creating a maze solving algorithm in Java

前端 未结 5 1374
萌比男神i
萌比男神i 2021-02-01 10:56

I\'ve been assigned with the task of creating a maze solver in Java. Here\'s the assignment:

Write an application that finds a path through a maze.  
The maze sh         


        
5条回答
  •  春和景丽
    2021-02-01 11:38

    As amit has said, you should first read the entire maze and store it as a 2 dimensional array. This lets you see the whole maze without having to solve it line-by-line.

    Since you'll first need to find the size of the array, you should read the text file into a List of Strings.

    List strs = new ArrayList();
    
    //Pseudocode, choose however you want to read the file
    while(file_has_next_line) {
        strs.add(get_next_line);
    }
    

    The size of the List gives you the number of rows, and assuming it's always a grid, you can use split().length, (count spaces + 1) or count the symbols on any one of the Strings to get the number of columns.

    Easiest way to store the map data is with a 2D array of booleans. Where true is a wall and false is empty space.

    boolean[][] wallMap = new boolean[rows][cols];
    
    for(int i = 0; i < wallMap.length; i++) {
    
        //Separate each symbol in corresponding line
        String[] rowSymbols = strs.get(i).split(" ");
    
        for(int j = 0; j < wallMap[i].length; j++) {
    
            //Ternary operator can be used here, I'm just keeping it simple
            if(rowSymbols[j].equals("X")) {
                 wallMap[i][j] = true;
            } else {
                 wallMap[i][j] = false;
            }
    
        }
    
    }
    

    Now that you have the map data stored in an array it's much easier to traverse the map and make your choices, you can either use a ready-made algorithm (see amit's answer) or make your own. As this is homework, you should try and think up your own.

    Have fun.

提交回复
热议问题