使用随机队列实现生成迷宫

前言

队列是一种先进先出的容器,随机队列就是顺序入队,随机出队。
生成的迷宫效果图如下:

自动解迷宫效果为

实现

可视化主类

import java.awt.EventQueue;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class AlgoVisualizer {

  private static int DELAY = 5;
  private static int blockSide = 6;

  private MazeData data;
  private AlgoFrame frame;
  private static final int d[][] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

  public AlgoVisualizer(int N, int M) {

    // 初始化数据
    data = new MazeData(N, M);
    int sceneHeight = data.N() * blockSide;
    int sceneWidth = data.M() * blockSide;

    // 初始化视图
    EventQueue.invokeLater(() -> {
      frame = new AlgoFrame("Random Maze Generation Visualization", sceneWidth, sceneHeight);
      frame.addKeyListener(new AlgoKeyListener());
      new Thread(this::run).start();
    });
  }

  private void run() {

    setData(-1, -1);

    RandomQueue queue = new RandomQueue();
    Position first = new Position(data.getEntranceX(), data.getEntranceY() + 1, -1, -1);
    queue.push(first);
    while (!queue.isEmpty()) {
      Position curPos = queue.pop();
      int x = curPos.getX();
      int y = curPos.getY();
      if (!data.inArea(x, y)) {
        continue;
      }
      if (data.visited[x][y]) {
        continue;
      }
      data.visited[x][y] = true;
      data.openMist(x, y);
      setData(curPos.getRoadX(), curPos.getRoadY());
      for (int i = 0; i < 4; i++) {
        int newX = x + d[i][0] * 2;
        int newY = y + d[i][1] * 2;
        queue.push(new Position(newX, newY, x + d[i][0], y + d[i][1]));
      }
    }

    setData(-1, -1);
  }

  private void setData(int x, int y) {
    if (data.inArea(x, y)) {
      data.maze[x][y] = MazeData.ROAD;
    }
    frame.render(data);
    AlgoVisHelper.pause(DELAY);
  }

  private void setData(int x, int y, boolean isPath) {
    if (data.inArea(x, y)) {
      data.path[x][y] = isPath;
    }

    frame.render(data);
    AlgoVisHelper.pause(DELAY);
  }

  // 从(x,y)的位置开始求解迷宫,如果求解成功,返回true;否则返回false
  private boolean go(int x, int y) {

    if (!data.inArea(x, y)) {
      return false;
    }
    if (data.isWall(x, y)) {
      return false;
    }
    if (data.visited[x][y]) {
      return false;
    }
    data.visited[x][y] = true;
    setData(x, y, true);

    if (x == data.getExitX() && y == data.getExitY()) {
      return true;
    }
    for (int i = 0; i < 4; i++) {
      int newX = x + d[i][0];
      int newY = y + d[i][1];
      if (go(newX, newY)) {
        return true;
      }
    }

    // 回溯
    setData(x, y, false);

    return false;
  }

  private class AlgoKeyListener extends KeyAdapter {

    @Override
    public void keyReleased(KeyEvent e) {
      if (e.getKeyChar() == ' ') {
        data.visitedReset();
        new Thread(() -> go(data.getEntranceX(), data.getEntranceY())).start();
      }
    }
  }

  public static void main(String[] args) {

    int N = 81;
    int M = 81;

    AlgoVisualizer vis = new AlgoVisualizer(N, M);

  }
}

窗口类

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class AlgoFrame extends JFrame {

  private int canvasWidth;
  private int canvasHeight;

  public AlgoFrame(String title, int canvasWidth, int canvasHeight) {

    super(title);

    this.canvasWidth = canvasWidth;
    this.canvasHeight = canvasHeight;

    AlgoCanvas canvas = new AlgoCanvas();
    setContentPane(canvas);
    pack();

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);

    setVisible(true);
  }

  public AlgoFrame(String title) {

    this(title, 1024, 768);
  }

  public int getCanvasWidth() {
    return canvasWidth;
  }

  public int getCanvasHeight() {
    return canvasHeight;
  }

  // data
  private MazeData data;

  public void render(MazeData data) {
    this.data = data;
    repaint();
  }

  private class AlgoCanvas extends JPanel {

    public AlgoCanvas() {
      // 双缓存
      super(true);
    }

    @Override
    public void paintComponent(Graphics g) {
      super.paintComponent(g);

      Graphics2D g2d = (Graphics2D) g;

      // 抗锯齿
      RenderingHints hints = new RenderingHints(
          RenderingHints.KEY_ANTIALIASING,
          RenderingHints.VALUE_ANTIALIAS_ON);
      hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
      g2d.addRenderingHints(hints);

      // 具体绘制
      int w = canvasWidth / data.M();
      int h = canvasHeight / data.N();

      for (int i = 0; i < data.N(); i++) {
        for (int j = 0; j < data.M(); j++) {
          if (data.inMist[i][j]) {
            AlgoVisHelper.setColor(g2d, AlgoVisHelper.Black);
          } else {
            if (data.maze[i][j] == MazeData.WALL) {
              AlgoVisHelper.setColor(g2d, AlgoVisHelper.LightBlue);
            } else {
              AlgoVisHelper.setColor(g2d, AlgoVisHelper.White);
            }
          }
          if (data.path[i][j]) {
            AlgoVisHelper.setColor(g2d, AlgoVisHelper.Yellow);
          }
          AlgoVisHelper.fillRectangle(g2d, j * w, i * h, w, h);
        }
      }
    }

    @Override
    public Dimension getPreferredSize() {
      return new Dimension(canvasWidth, canvasHeight);
    }
  }
}

工具类

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;


public class AlgoVisHelper {

  private AlgoVisHelper() {
  }

  public static final Color Red = new Color(0xF44336);
  public static final Color Pink = new Color(0xE91E63);
  public static final Color Purple = new Color(0x9C27B0);
  public static final Color DeepPurple = new Color(0x673AB7);
  public static final Color Indigo = new Color(0x3F51B5);
  public static final Color Blue = new Color(0x2196F3);
  public static final Color LightBlue = new Color(0x03A9F4);
  public static final Color Cyan = new Color(0x00BCD4);
  public static final Color Teal = new Color(0x009688);
  public static final Color Green = new Color(0x4CAF50);
  public static final Color LightGreen = new Color(0x8BC34A);
  public static final Color Lime = new Color(0xCDDC39);
  public static final Color Yellow = new Color(0xFFEB3B);
  public static final Color Amber = new Color(0xFFC107);
  public static final Color Orange = new Color(0xFF9800);
  public static final Color DeepOrange = new Color(0xFF5722);
  public static final Color Brown = new Color(0x795548);
  public static final Color Grey = new Color(0x9E9E9E);
  public static final Color BlueGrey = new Color(0x607D8B);
  public static final Color Black = new Color(0x000000);
  public static final Color White = new Color(0xFFFFFF);


  public static void strokeCircle(Graphics2D g, int x, int y, int r) {

    Ellipse2D circle = new Ellipse2D.Double(x - r, y - r, 2 * r, 2 * r);
    g.draw(circle);
  }

  public static void fillCircle(Graphics2D g, int x, int y, int r) {

    Ellipse2D circle = new Ellipse2D.Double(x - r, y - r, 2 * r, 2 * r);
    g.fill(circle);
  }

  public static void strokeRectangle(Graphics2D g, int x, int y, int w, int h) {

    Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);
    g.draw(rectangle);
  }

  public static void fillRectangle(Graphics2D g, int x, int y, int w, int h) {

    Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);
    g.fill(rectangle);
  }

  public static void setColor(Graphics2D g, Color color) {
    g.setColor(color);
  }

  public static void setStrokeWidth(Graphics2D g, int w) {
    int strokeWidth = w;
    g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
  }

  public static void pause(int t) {
    try {
      Thread.sleep(t);
    } catch (InterruptedException e) {
      System.out.println("Error sleeping");
    }
  }

}

数据类

import java.util.Arrays;

public class MazeData {

  public static final char ROAD = ' ';
  public static final char WALL = '#';

  private int N, M;
  public char[][] maze;
  public boolean[][] visited;
  public boolean[][] path;
  public boolean[][] inMist;

  private int entranceX, entranceY;
  private int exitX, exitY;

  public MazeData(int N, int M) {

    if (N % 2 == 0 || M % 2 == 0) {
      throw new IllegalArgumentException(
          "Our Maze Generalization Algorihtm requires the width and height of the maze are odd numbers");
    }

    this.N = N;
    this.M = M;

    maze = new char[N][M];
    path = new boolean[N][M];
    visited = new boolean[N][M];
    inMist = new boolean[N][M];
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < M; j++) {
        if (i % 2 == 1 && j % 2 == 1) {
          maze[i][j] = ROAD;
        } else {
          maze[i][j] = WALL;
        }

        visited[i][j] = false;
        inMist[i][j] = true;
      }
    }

    entranceX = 1;
    entranceY = 0;
    exitX = N - 2;
    exitY = M - 1;

    maze[entranceX][entranceY] = ROAD;
    maze[exitX][exitY] = ROAD;
  }

  public int N() {
    return N;
  }

  public int M() {
    return M;
  }

  public int getEntranceX() {
    return entranceX;
  }

  public int getEntranceY() {
    return entranceY;
  }

  public int getExitX() {
    return exitX;
  }

  public int getExitY() {
    return exitY;
  }

  public boolean inArea(int x, int y) {
    return x >= 0 && x < N && y >= 0 && y < M;
  }

  public boolean isWall(int i, int j) {
    return maze[i][j] == WALL;
  }

  public boolean isRoad(int i, int j) {
    return maze[i][j] == ROAD;
  }

  public void visitedReset() {
    for (boolean[] data : visited) {
      Arrays.fill(data, false);
    }
  }

  public void openMist(int x, int y) {
    if (!inArea(x, y)) {
      throw new IllegalArgumentException("x or y is out of index in openMist function!");
    }
    for (int i = x - 1; i <= x + 1; i++) {
      for (int j = y - 1; j <= y + 1; j++) {
        if (inArea(i, j)) {
          inMist[i][j] = false;
        }
      }
    }
  }
}
public class Position {

  private int x, y;
  private int roadX, roadY;

  public Position(int x, int y, int roadX, int roadY) {
    this.x = x;
    this.y = y;
    this.roadX = roadX;
    this.roadY = roadY;
  }

  public int getX() {
    return x;
  }

  public int getY() {
    return y;
  }

  public int getRoadX() {
    return roadX;
  }

  public int getRoadY() {
    return roadY;
  }
}

随机队列

import java.util.Deque;
import java.util.LinkedList;

public class RandomQueue {

  private Deque<Position> positionList;

  public RandomQueue() {
    positionList = new LinkedList<>();
  }

  public void push(Position position) {
    if (Math.random() > 0.5) {
      positionList.addFirst(position);
    } else {
      positionList.addLast(position);
    }
  }

  public Position pop() {
    if (Math.random() > 0.5) {
      return positionList.removeFirst();
    } else {
      return positionList.removeLast();
    }
  }

  public boolean isEmpty() {
    return positionList.isEmpty();
  }
}

创建迷宫和解迷宫使用的主要是回溯的思想,生成迷宫之后点击空格键开始自动走迷宫。

posted @ 2021-04-03 14:43  strongmore  阅读(463)  评论(0编辑  收藏  举报