Java迷宫打破封闭

标签 java optimization closures clone

我有下一堂迷宫课。我只需要添加一项优化。如果for循环中没有maze = readFromFile();,则方法check仅运行一次,因为maze数组在check方法中被修改。我想避免每次迭代都从文件中读取。我正在尝试复制我的 maze 数组以避免它发生变异,但没有成功。

public class Maze {
    private static char[][] maze;
    private static int size;
    private static Cell startCell = null;
    private static ArrayList<String> resultPaths = new ArrayList<>();
    private static final String INPUT_FILE_NAME = "Problem.in";
    private static final String OUTPUT_FILE_NAME = "Problem.out";
    private static char[][] readFromFile() throws FileNotFoundException {
        Scanner scanner = new Scanner(new File(Maze.INPUT_FILE_NAME));
        try {
            // Read maze size
            size = scanner.nextInt();
            scanner.nextLine();
            // Create the maze
            maze = new char[size][size];
            // Read the maze cells from the file
            for (int row = 0; row < size; row++) {
                String line = scanner.nextLine();
                for (int col = 0; col < line.length(); col++) {
                    char ch = line.charAt(col);
                    maze[row][col] = ch;
                    if (ch == '*') {
                        startCell = new Cell(row, col);
                    }
                }
            }
            return maze;
        } finally {
            scanner.close();
        }
    }

    public static void saveResult(String fileName, ArrayList<String> resultPaths) throws IOException {
        FileWriter writer = new FileWriter(fileName);
        try {
            for (String resultPath : resultPaths) {
                writer.write("" + resultPath + "\n");
            }
        } finally {
            writer.close();
        }
    }

    private static void check(int x, int y, int dest_x, int dest_y, char[][] maze, String path) {
        if (x < 0 || y < 0 || x >= size || y >= size || maze[y][x] == '#') {
            return;
        }
        if (maze[y][x] != '*') {
            path += String.valueOf(maze[y][x]);
        }

        if (x == dest_x && y == dest_y) {
            System.out.println(path);
            resultPaths.add(path);
            return;
        } else {
            maze[y][x] = '#';
            check (x + 0, y - 1, dest_x, dest_y, maze, path);
            check (x + 0, y + 1, dest_x, dest_y, maze, path);
            check (x - 1, y + 0, dest_x, dest_y, maze, path);
            check (x + 1, y + 0, dest_x, dest_y, maze, path);
            maze[y][x] = '#';
        }
    }

    public static ArrayList<Cell> getExits(char[][] maze) {
        ArrayList<Cell> result = new ArrayList<>();
        for (int row = 0; row < size; row++) {
            for (int col = 0; col < size; col++) {
                char ch = maze[row][col];
                maze[row][col] = ch;
                if (ch == '*') {
                    startCell = new Cell(row, col);
                }
                if ((ch != '#') && (row == 0 || col == 0 || row == (size - 1) || col == (size - 1))) {
                    result.add(new Cell(row, col));
                }
            }
        }
        return result;
    }

    public static void main(String[] args) throws IOException {
        maze = readFromFile();
        ArrayList<Cell> possibleExits = getExits(maze);
        String path = "";
        for (Cell currentCell : possibleExits) {
            maze = readFromFile(); // HERE I NEED TO REPLACE THIS WITH COPY OF CURRENT MAZE CHAR ARRAY
            check(startCell.getCol(), startCell.getRow(), currentCell.getCol(), currentCell.getRow(), maze, path);
        }
        saveResult(OUTPUT_FILE_NAME, resultPaths);
    }
}

输入文件:

6
a##km#
z#ada#
a*m###
#d####
rifid#
#d#d#t

输出:

aza
madk
madamk
madkm
madam
az
a
dir
did
difid

最佳答案

你可以在copyMaze上进行操作,并且cleanMaze不会改变,你可以在每次需要新迷宫时进行复制。从文件中读取 cleanMaze 后切勿对其进行修改。

final char[][] cleanMaze = readFromFile(); // never modify this again

char[][] copyMaze = new char[size][size];
for (int i = 0; i < size; i++) {
  System.arraycopy(cleanMaze[i], 0, copyMaze[i], 0, size);
}

System.arracopy javadoc

不要试图将副本从循环中取出,这是行不通的。它只会复制第一维,第二维的修改会修改两个数组中的它,这就是为什么我们需要复制所有内容。

关于Java迷宫打破封闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56716301/

相关文章:

arrays - 递增 : x++ vs x += 1

javascript - 如果 Javascript 中的 "with"语句创建了一个新的作用域,为什么这个闭包每次都不包含新作用域中的新的 "x"?

java - 错误; java.lang.IllegalStateException : Cannot create a session after the response has been committed

java - 检查实例是否是父类而不是子类的最佳方法?

java - 转换组件[] -> JButton

java - 为什么在 Java 中使用 StringBuffer 而不是字符串连接运算符

c - 找出可以形成的正方形数

rust - 具有包含异步 block 的闭包的异步方法无法推断适当的生存期

c# - DLR LambdaExpressions 和 System.Runtime.CompilerServices.Closure 对象

java - Spigot 插件尝试包含 Apache Commons Text 时出现 NoClassDefFoundError