本帖最后由 匿名 于 2021-6-19 15:02 编辑
[i]- int[][] DIR = new int[][] {
- {-1, 0},
- {0, 1},
- {0, -1},
- {1, 0}
- };
- public int[][] mazeGenerator(int height, int width, int[] start, int[] end) {
- int[][] maze = new int[height][width];
- List<int[]> path = new ArrayList<>();
- dfs(start[0], start[1], end, visited, path);
- Random random = new Random();
- for(int[] point : path) {
- maze[point[0]][point[1]] = 1;
- }
- for(int i = 0; i < height; ++i) {
- for(int j = 0; j < width; ++j) {
- if(maze[i][j] == 1) continue;
- maze[i][j] = random.nextInt(2);
- }
- }
- return maze;
- }
- private boolean dfs(int h, int w, int[] end, boolean[][] visited, List<int[]> path) {
- if(h < 0 || h == visited.length || w < 0 || w == visited[0].length || visited[h][w]) return false;
- visited[h][w] = true;
- path.add(new int[]{h, w});
- if(h == end[0] && w == end[1]) return true;
- for(int[] dir : DIR) {
- if(dfs(maze, h + dir[0], w + dir[1], end, visited, path)) return true;
- }
- visited[h][w] = false;
- path.remove(path.size() - 1);
- return false;
- }
- /*
- Followup:
- 其实就是每次把dfs内部用来存放移动方向的DIR在每次call dfs的时候shuffle下.
- 具体实现随意.
- */
复制代码
[/i] |