在java中解决迷宫

时间:2017-01-12 05:58:42

标签: java search maze

我正在尝试使用BFS或DFS解决迷宫,迷宫编号在文本文件中给出,因此我必须逐行读取然后将每个字符串转换为整数并将每行存储在大小为2的数组中我将这个数组存储在arraylist中。 其次,在findRow方法中,我尝试搜索数组中的每个元素,并向左或向右打印出与其相关的数字。 但我的主要目标是使用任何搜索方法以最快的方式打印到迷宫的尽头。文本文件的格式为0,1表示起始节点和结束节点。 11 3 2 3 0 3 1 4 5 4 5 7 6 7 7 8 8 9 9 10 0 5

=====

我的代码

public class Mazes {
    ArrayList<int[]> collections = new ArrayList();

    public String toString() {
        String result = "";

        for (int i = 0; i < collections.size(); i++) {
            result += collections.get(i)[0];
            result += " ";
            result += collections.get(i)[1];
            result += "\n";
        }
        return result;
    }

    public void getMazes() throws Exception{
        try{
            FileInputStream fstream = new FileInputStream("C:\\csd3939\\maze1.txt");
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

            while((strLine = br.readLine()) !=  null){
                String[] splitStringArray = strLine.split(" ");
                int[] intElementArray = new int[2];
                for(int i=0; i<splitStringArray.length; i++){
                    intElementArray[i] = Integer.parseInt(splitStringArray[i]);                     }
                collections.add(intElementArray);
            }
            System.out.print("\n");
            in.close();

        }catch (Exception e){
            System.err.println("Error: " + e.getMessage());
        }
    }

    public ArrayList<Integer> findRowConnection(int rowID){
        ArrayList<Integer> connectRow = new ArrayList();
        for(int i=0; i<collections.size(); i++){
            int[] searching = collections.get(i);
            if(rowID == searching[0]){
                connectRow.add(searching[1]);
            }
            if(rowID == searching[1]){
                connectRow.add(searching[0]);
            }
        }
        return connectRow;
    }
}

===========
main method
===========

public class MazeMain {
    public static void main(String[] args)throws Exception{
        Mazes mainmaze = new Mazes();
        mainmaze.getMazes();
        System.out.println(mainmaze);
        ArrayList<Integer> searchResult = mainmaze.findRowConnection(0);

        System.out.println("Connected Rows are :");
        for(int i=0; i<searchResult.size(); i++){
            System.out.println(searchResult.get(i));
        }
    }
}

0 个答案:

没有答案