任务1
- 题目
尝试使用图来表示迷宫,并利用图的最小支撑树算法完成迷宫的生成。假如迷宫的大小为n*n,此时可以将迷宫表示成一个n*n 的矩阵。为了使用图解决问题,首先需要将迷宫表示成一个图G,其中迷宫中的每一个单元格对应图G 中的一个顶点,单元格i 和单元格j 之间有共享边时,则对应图G 中顶点i 和顶点j 有边相连。当将迷宫以图的抽象表示出来之后,就可以使用图的算法完成问题的求解了。本次实验中涉及到图数据结构的具体实现,Kruskal算法的实现以及Dijkstra最短路径算法的实现,请按照如下子任务的顺序完成本实验。
该任务的主要内容是完成用图数据结构对迷宫的表示实现,成功表示之后,可以使用如下两个策略生成迷宫:
策略 1:随机擦除 70%的图中的边;
策略 2:随机擦除 50%的图中的边;
针对不同的策略,使用 Dijkstra 算法检测所生成的迷宫从入口(左上角)到出口(右下角)是否有路径可达。对每一个策略可以执行 100 次,给出成功生成迷宫的概率(成功即代表从入口到出口一定有路径可达)。
- 数据设计
数据结构包括一个底层的GraphM图,我是使用相邻矩阵实现的无向图,以及一个Cell,指的是图中每一个格子。
首先是GraphM图:
GraphM类包括一个int[][] matrix 表示相邻矩阵;一个int E表示边数;一个private ArrayList<Integer> V表示顶点。
- public class GraphM {
- //用相邻矩阵实现无向图
- private ArrayList<Integer> V;//顶点
- private int E;//边数
- private int[][] matrix;//相邻矩阵
- }
构造函数接受一个整数参数n,表示图中的节点数,创建一个大小为n×n的二维整数数组matrix来表示图的邻接矩阵,并创建一个大小为n的整数列表V来存储图的节点。
- /**
- * 初始化无向图
- * @param n 结点数
- */
- public GraphM(int n) {
- matrix = new int[n][n];
- V = new ArrayList<Integer>(n);
- }
insertVertex(Integer vertex)方法用于添加节点,首先接受一个整数参数vertex,表示要添加的节点的值,再将节点的值添加到节点列表V中。
insertEdge(int v1, int v2, int weight)方法用于插入边。它接受三个参数,v1和v2分别表示边的起点和终点的下标,weight表示边的权值。在这个方法中,通过将matrix[v1][v2]和matrix[v2][v1]设置为给定的权值,将节点v1和节点v2之间的边添加到邻接矩阵中。由于这是无向图,所以同时也将节点v2和节点v1之间的边添加到邻接矩阵中。同时,边的数量E增加1。
- /**
- * 添加结点
- * @param vertex 结点值
- */
- public void insertVertex(Integer vertex){
- V.add(vertex);
- }
- /**
- * 插入边
- * @param v1 起点下标
- * @param v2 终点下标
- * @param weight 权值,这里1表示相邻,1000表示不相邻
- */
- public void insertEdge(int v1,int v2,int weight) {
- matrix[v1][v2] = weight;
- matrix[v2][v1] = weight;
- E++;//边数+1
- }
Output方法是将邻接矩阵的对应行输出,是为了后续方法实现所实现的方法。
- public int[] output(int row){
- return matrix[row];
- }
还有几个方法并没有用到,不再赘述。
- /**
- * 获得v1->v2的权值
- * @param v1
- * @param v2
- * @return
- */
- public int getWeight(int v1,int v2){
- return matrix[v1][v2];
- }
- /**
- * 获得边的数量
- * @return
- */
- public int getEdgeNum(){
- return E;
- }
- /**
- * 获得结点数
- * @return
- */
- public int getVertexNum(){
- return V.size();
- }
Cell类型指的是每一个格子,具体实现如下:
Cell包括x和y表示格子的位置在第几行第几列,right和down表示这个格子与右面下面的格子是否有边,规定,如果有边,那么对应的值为1,否则为1000.
- class Cell {
- private int x; // 格子的位置,在第几行
- private int y; // 第几列
- //1 代表 有边 1000 代表 无边
- private int right;
- private int down;
- }
Cell的构造方法是传入x和y,以及各种get和set方法,这里不再赘述,直接贴出代码。
- class Cell {
- private int x; // 格子的位置,在第几行
- private int y; // 第几列
- private int flag = Constants.NOTINTREE; // flag,标识格子是否已加入树中
- private Cell father = null; // 格子的父亲节点
- //1 代表 有边 1000 代表 无边
- private int right;
- private int down;
- public Cell(int xx, int yy) {
- x = xx;
- y = yy;
- }
- public int getX() {
- return x;
- }
- public void setX(int x) {
- this.x = x;
- }
- public int getY() {
- return y;
- }
- public void setY(int y) {
- this.y = y;
- }
- public int getFlag() {
- return flag;
- }
- public void setFlag(int flag) {
- this.flag = flag;
- }
- public Cell getFather() {
- return father;
- }
- public void setFather(Cell father) {
- this.father = father;
- }
- public int getRight() {
- return right;
- }
- public void setRight(int right) {
- this.right = right;
- }
- public int getDown() {
- return down;
- }
- public void setDown(int down) {
- this.down = down;
- }
- }
- 算法设计
整个算法是这样一个思路,对于第一问,我们需要生成抽象的图G和一个显示出来的图Puzzle,这个Puzzle实际数据类型是int[][],而图G本质也是邻接矩阵int[][],但是这两个矩阵也并不相同,两者有一定割裂;为了解决消除“边”的操作,我们还需要down和right两个int[][],当里面的数为1时,表示格子相邻,距离为1,当数为1000时表示格子不相邻,距离为1000无穷大。
而整个应用实现也包括前端和后端,前端是根据Puzzle进行绘制的,后端是根据图G生成的,因此考虑分两个类Puzzle和Test分别做后端和前端。
在Puzzle类中包括down和right两个int[][],以及一个图G。
- public class Puzzle {
- public GraphM graph;
- //down,right数组存储格子的上下左右四条边
- int[][] down = new int[Constants.GRID_SIZE][Constants.GRID_SIZE];
- int[][] right = new int[Constants.GRID_SIZE][Constants.GRID_SIZE];
- }
我们要实现newPuzzle()方法,得到down和right数组以及图G;而getPath()方法会根据实现的图G根据Kruskal算法得到一个List保存迷宫的路径。
newPuzzle()方法概述:
- 初始化down和right两个数组为1000.
- 根据比例随机down和right两个数组部分数为1.
- 创建抽象图G,定义图G的所有顶点,创建图并把顶点添加到图中。
- 根据down和right两个数组将边添加到图G中。
newPuzzle()方法详细介绍:
- 初始化down和right两个数组为1000.
- //1.数组全1000表示完整格子
- for (int i = 0; i < Constants.GRID_SIZE; i++) {
- for (int j = 0; j < Constants.GRID_SIZE; j++) {
- down[i][j] = Constants.INNEIGHBOURING;
- right[i][j] = Constants.INNEIGHBOURING;
- }
- }
- 根据比例随机down和right两个数组部分数为1.
- //2.随机down和right两个数组
- randomizeArray(down);
- randomizeArray(right);
- private static void randomizeArray(int[][] array) {
- Random random = new Random();
- int totalCells = Constants.GRID_SIZE * Constants.GRID_SIZE;
- int numZeroes = (int) (Constants.RANDOMPERCENTAGE * totalCells);
- while (numZeroes > 0) {
- int randomRow = random.nextInt(Constants.GRID_SIZE);
- int randomCol = random.nextInt(Constants.GRID_SIZE);
- if (array[randomRow][randomCol] != Constants.NEIGHBOURING) {
- array[randomRow][randomCol] = Constants.NEIGHBOURING;
- numZeroes--;
- }
- }
- }
- 创建抽象图G,定义图G的所有顶点,创建图并把顶点添加到图中。
- //3.创建抽象的全连接的图
- //定义图的所有顶点
- Integer[] vertexs = new Integer[Constants.GRID_SIZE * Constants.GRID_SIZE];
- for (int i = 0; i < vertexs.length; i++) {
- vertexs[i] = i;
- }
- //创建图
- graph = new GraphM(vertexs.length);
- //添加顶点到图中
- for (Integer vertex : vertexs) {
- graph.insertVertex(vertex);
- }
- 根据down和right两个数组将边添加到图G中。
- //4.根据down和right两个数组添加边到图中
- for (int i = 0; i < Constants.GRID_SIZE - 1; i++) {
- for (int j = 0; j < Constants.GRID_SIZE; j++) {
- //对于down数组
- if(down[i][j] == Constants.INNEIGHBOURING){
- graph.insertEdge(i * Constants.GRID_SIZE + j, ( i + 1 ) * Constants.GRID_SIZE + j, Constants.INNEIGHBOURING);
- }else{
- graph.insertEdge(i * Constants.GRID_SIZE + j, ( i + 1 ) * Constants.GRID_SIZE + j, Constants.NEIGHBOURING);
- }
- }
- }
- for (int i = 0; i < Constants.GRID_SIZE; i++) {
- for (int j = 0; j < Constants.GRID_SIZE - 1; j++) {
- if(right[i][j] == Constants.INNEIGHBOURING){
- graph.insertEdge(i * Constants.GRID_SIZE + j, i * Constants.GRID_SIZE + j + 1, Constants.INNEIGHBOURING);
- }else{
- graph.insertEdge(i * Constants.GRID_SIZE + j, i * Constants.GRID_SIZE + j + 1, Constants.NEIGHBOURING);
- }
- }
- }
getPath()方法概述:
- 构建图的邻接矩阵。
- 导入图G的邻接矩阵。
- 调用DijkstraAlgorithm类的方法生成对应的路径。
getPath()方法详细讲解:
- 构建图的邻接矩阵。
- // 构建图的邻接矩阵表示
- List<List<Integer>> adjacentMatrix = new ArrayList<>();
- 导入图G的邻接矩阵。
- // 导入图的链接矩阵
- for (int i = 0; i < Constants.GRID_SIZE * Constants.GRID_SIZE; i++) {
- int[] array = graph.output(i);
- List<Integer> row = new ArrayList<>();
- for (int value : array) {
- row.add(value);
- }
- adjacentMatrix.add(row);
- }
- 调用DijkstraAlgorithm类的方法生成对应的路径。
- // 调用方法
- DijkstraAlgorithm dijkstraAlgorithm = new DijkstraAlgorithm();
- int source = 0;
- List<Integer> Path = dijkstraAlgorithm.getShortestPath(adjacentMatrix, source, Constants.GRID_SIZE * Constants.GRID_SIZE - 1);
- return Path;
Puzzle类中使用了DijkstraAlgorithm类中的方法,Dijkstra算法是一种用于在带权重的图中找到从源节点到目标节点的最短路径的经典算法,算法的核心思想是通过不断更新节点之间的距离来逐步找到最短路径。它维护两个列表:一个是距离列表,用于存储从源节点到每个节点的最短距离;另一个是访问标记列表,用于标记节点是否已经被访问过。
算法的步骤如下:
初始化距离列表和访问标记列表。将源节点的距离设置为0,其他节点的距离设置为无穷大,访问标记设置为false。
选择一个未访问的节点中距离最小的节点,并将其标记为已访问。
遍历该节点的所有邻居节点,并更新从源节点到邻居节点的距离。如果通过当前节点到邻居节点的路径距离比之前计算的距离更短,更新距离列表和路径列表。
重复步骤2和步骤3,直到所有节点都被访问过或者没有可达节点。
该实现还提供了一个getShortestPath方法,用于获取从源节点到目标节点的最短路径。它首先调用dijkstra方法获取最短距离列表,然后从目标节点开始沿着最短路径倒序回溯,直到回溯到源节点,以获取完整的最短路径。
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- public class DijkstraAlgorithm {
- private static final int INF = 500;
- public List<Integer> dijkstra(List<List<Integer>> G, int source) {
- int n = G.size();
- List<Integer> dis = new ArrayList<>(n);
- List<Boolean> vis = new ArrayList<>(n);
- for (int i = 0; i < n; i++) {
- dis.add(INF);
- vis.add(false);
- }
- dis.set(source, 0);
- List<List<Integer>> paths = new ArrayList<>(n); // 存储节点0到每个节点的具体路径
- for (int i = 0; i < n; i++) {
- paths.add(new ArrayList<>());
- }
- paths.get(source).add(source); // 初始路径为只包含起始节点
- for (int i = 0; i < n - 1; i++) {
- int node = -1;
- for (int j = 0; j < n; j++) {
- if (!vis.get(j) && (node == -1 || dis.get(j) < dis.get(node))) {
- node = j;
- }
- }
- for (int j = 0; j < n; j++) {
- int weight = G.get(node).get(j);
- if (weight != 0) { // Consider the presence of an edge as weight 1
- if (dis.get(node) + weight < dis.get(j)) {
- dis.set(j, dis.get(node) + weight);
- paths.get(j).clear();
- paths.get(j).addAll(paths.get(node));
- paths.get(j).add(j);
- }
- }
- }
- vis.set(node, true);
- }
- return dis;
- }
- public List<Integer> getShortestPath(List<List<Integer>> G, int source, int destination) {
- List<Integer> dis = dijkstra(G, source);
- List<Integer> path = new ArrayList<>();
- if (dis.get(destination) == INF) {
- return path;
- }
- int current = destination;
- path.add(current);
- while (current != source) {
- int prev = -1;
- int minWeight = INF;
- for (int neighbor = 0; neighbor < G.size(); neighbor++) {
- int weight = G.get(neighbor).get(current);
- if (weight != 0 && dis.get(neighbor) + weight == dis.get(current)) {
- prev = neighbor;
- break;
- }
- }
- if (prev == -1) {
- return path;
- }
- path.add(prev);
- current = prev;
- }
- Collections.reverse(path);
- return path;
- }
- }
Test类继承自JPanel,Test类包括public int padding表示图距边框的距离;public int width表示每一个Cell的宽度;public Cell[][] maze表示储存Cell的格子;public Puzzle puzzle是迷宫;private int numberFailtures表示没有路径的次数;private int numberTry 表示总的实验次数。
- public class Test extends JPanel {
- public int padding = Constants.PADDING;
- public int width = (Constants.WIDTH - Constants.PADDING - Constants.PADDING) / Constants.GRID_SIZE;
- public Cell[][] maze;
- public Puzzle puzzle;
- private int numberFailtures = 0;
- private int numberTry = 0;
- }
paintComponent是Java Swing框架中的一个方法,它用于在组件上绘制可视化内容。它是在自定义组件中重写的一个方法,用于定义如何绘制组件的外观,paintComponent方法会在组件需要重新绘制时自动调用,允许使用Graphics对象进行绘制操作,以实现自定义的界面效果和可视化内容。
paintComponent方法概述:
- 绘制完整的格子。
- 使用背景色,根据Puzzle中的数组,在有路径的格子之间画边,把墙抹掉。
- 绘制左上角和右下角的出口。
- 绘制下边框和右边框
- 绘制正确路径。
paintComponent方法详细解释:
- 绘制完整的格子。
- super.paintComponent(g);
- // 画NUM*NUM条黑线
- for (int i = 0; i <= Constants.GRID_SIZE; i++) {
- g.drawLine(padding + i * width, padding, padding + i * width,
- padding + Constants.GRID_SIZE * width);
- }
- for (int j = 0; j <= Constants.GRID_SIZE; j++) {
- g.drawLine(padding, padding + j * width, padding + Constants.GRID_SIZE * width,
- padding + j * width);
- }
- 使用背景色,根据Puzzle中的数组,在有路径的格子之间画边,把墙抹掉。
- // 使用背景色,在有路径的格子之间画边,把墙抹掉
- g.setColor(this.getBackground());
- //根据Puzzle中的数组进行抹边
- for (int i = 0; i < Constants.GRID_SIZE; i++) {
- for (int j = 0; j < Constants.GRID_SIZE; j++) {
- maze[i][j] = new Cell(i, j);
- if (puzzle.down[i][j] == Constants.NEIGHBOURING) {
- maze[i][j].setDown(Constants.NEIGHBOURING);
- }
- if (puzzle.down[i][j] == Constants.INNEIGHBOURING) {
- maze[i][j].setDown(Constants.INNEIGHBOURING);
- }
- if (puzzle.right[i][j] == Constants.NEIGHBOURING) {
- maze[i][j].setRight(Constants.NEIGHBOURING);
- }
- if (puzzle.right[i][j] == Constants.INNEIGHBOURING) {
- maze[i][j].setRight(Constants.INNEIGHBOURING);
- }
- }
- }
- for (int i = Constants.GRID_SIZE - 1; i >= 0; i--) {
- for (int j = Constants.GRID_SIZE - 1; j >= 0; j--) {
- if (maze[i][j].getRight() == Constants.NEIGHBOURING) {
- clearFence(i, j, i, j + 1, g);
- }
- if (maze[i][j].getDown() == Constants.NEIGHBOURING) {
- clearFence(i, j, i + 1, j, g);
- }
- }
- }
- // 私有方法,目的是抹掉两个格子之间的边
- private void clearFence(int i, int j, int fx, int fy, Graphics g) {
- int sx = padding + ((j > fy ? j : fy) * width),
- sy = padding + ((i > fx ? i : fx) * width),
- dx = (i == fx ? sx : sx + width),
- dy = (i == fx ? sy + width : sy);
- if (sx != dx) {
- sx++;
- dx--;
- } else {
- sy++;
- dy--;
- }
- g.drawLine(sx, sy, dx, dy);
- }
- 绘制左上角和右下角的出口。
- // 画左上角的入口
- g.drawLine(padding, padding + 1, padding, padding + width - 1);
- int last = padding + Constants.GRID_SIZE * width;
- // 画右下角出口
- g.drawLine(last, last - 1, last, last - width + 1);
- 绘制下边框和右边框
- // 画下边框
- g.setColor(Color.BLACK);
- g.drawLine(padding, last, last, last);
- // 画右边框
- g.drawLine(last, padding, last, last - width);
- 绘制正确路径。
- // 画路径
- drawPath(g);
- private void drawPath(Graphics g) {
- g.setColor(Color.red);
- // 已经得到初始路径到最后路径的list,接下来对照相应的格子,再画出来就行
- List<Integer> path = puzzle.getPath();
- for (int i = 0; i < path.size() - 1; i++) {
- int first = path.get(i);
- int second = path.get(i + 1);
- g.drawLine(getCenterX(maze[getRow(first)][getCol(first)]),getCenterY(maze[getRow(first)][getCol(first)]),getCenterX(maze[getRow(second)][getCol(second)]),getCenterY(maze[getRow(second)][getCol(second)]));
- }
- }
由序列数得到对应的行和列。
- // 由序列数得到对应的行和列
- private int getRow(int num) {
- return (num - 1) / Constants.GRID_SIZE;
- }
- private int getCol(int num) {
- return num % Constants.GRID_SIZE;
- }
由格子的行数列数,得到格子中心点的像素XY坐标
- // 由格子的行数列数,得到格子中心点的像素XY坐标
- private int getCenterX(Cell p) {
- return padding + p.getY() * width + width / 2;
- }
- private int getCenterY(Cell p) {
- return padding + p.getX() * width + width / 2;
- }
Count方法,核心就是新生成一个Puzzle,并计算这个Puzzle有没有解,如果无解就令numberFailtures++。
- private void count() {
- //方便统计
- Puzzle p = new Puzzle();
- p.newPuzzle();
- List<Integer> path = p.getPath();
- numberTry++;
- if (path.isEmpty()) {
- numberFailtures++;
- }
- }
Test方法,生成了一个Puzzle并作图,然后反复调用100次count方法并输出迷宫的成功率。
- Test() {
- maze = new Cell[Constants.GRID_SIZE][Constants.GRID_SIZE];
- puzzle = new Puzzle();
- puzzle.newPuzzle();
- for (int i = 0; i < 100; i++) {
- count();
- }
- System.out.println("迷宫成功率为" + (double) (100 - (numberFailtures / numberTry * 100)) + " %");
- }
除此之外,我先为当前应用中很多类需要使用的常量完成定义,这样做更加易于维护,后续修改代码会方便很多。
- /**
- * 为当前应用中很多类需要使用的常量完成定义
- * 将逻辑上相关联的一组类所需要的常量定义在一个类中是可以借鉴的,这样易于维护。
- */
- public class Constants {
- /** 定义面板的每一行的单元格数 */
- public static final int GRID_SIZE = 40;
- /** 定义面板的大小 */
- public static final int WIDTH = 600;
- /** 定义面板的padding */
- public static final int PADDING = 10;
- /** 在树中 */
- public static final int INTREE = 1;
- /** 不在树中*/
- public static final int NOTINTREE = 0;
- /** 显示在屏幕上的位置 */
- public static final int LX = 450;
- public static final int LY = 100;
- /** 随机消除百分比 */
- public static final double RANDOMPERCENTAGE = 0.7;
- /** 权值,这里1表示相邻,1000表示不相邻 */
- public static final int NEIGHBOURING = 1;
- public static final int INNEIGHBOURING = 1000;
- }
- 运行结果展示
主函数进行测试:
- public static void main(String[] args) {
- JFrame frame = new JFrame("Maze");
- JPanel test = new Test();
- //下面一行自动调用paintComponent方法
- frame.setContentPane(test);
- frame.setSize(Constants.WIDTH + Constants.PADDING, Constants.WIDTH + Constants.PADDING + Constants.PADDING);
- frame.setLocation(Constants.LX, Constants.LY);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setVisible(true);
- }
结果如下:

图1 成功结果图

图2 失败结果图
随机擦除 70%的图中的边时成功几率较大,约为60%-75%
结果如下:

图3 随机擦除 70%的图中的边时迷宫成功率
随机擦除 50%的图中的边时成功几率极小,约为0%-1%
结果如下:
![]()
图4 随机擦除 50%的图中的边时迷宫成功率
- 总结和收获
通过这个实验,学习了Java Swing框架中paintComponent方法的使用,也复习了图的数据结构,复习了Dijkstra 算法,收获很大。
附录:
- 任务1
- DijkstraAlgorithm算法:
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- public class DijkstraAlgorithm {
- private static final int INF = 500;
- public List<Integer> dijkstra(List<List<Integer>> G, int source) {
- int n = G.size();
- List<Integer> dis = new ArrayList<>(n);
- List<Boolean> vis = new ArrayList<>(n);
- for (int i = 0; i < n; i++) {
- dis.add(INF);
- vis.add(false);
- }
- dis.set(source, 0);
- List<List<Integer>> paths = new ArrayList<>(n); // 存储节点0到每个节点的具体路径
- for (int i = 0; i < n; i++) {
- paths.add(new ArrayList<>());
- }
- paths.get(source).add(source); // 初始路径为只包含起始节点
- for (int i = 0; i < n - 1; i++) {
- int node = -1;
- for (int j = 0; j < n; j++) {
- if (!vis.get(j) && (node == -1 || dis.get(j) < dis.get(node))) {
- node = j;
- }
- }
- for (int j = 0; j < n; j++) {
- int weight = G.get(node).get(j);
- if (weight != 0) { // Consider the presence of an edge as weight 1
- if (dis.get(node) + weight < dis.get(j)) {
- dis.set(j, dis.get(node) + weight);
- paths.get(j).clear();
- paths.get(j).addAll(paths.get(node));
- paths.get(j).add(j);
- }
- }
- }
- vis.set(node, true);
- }
- return dis;
- }
- public List<Integer> getShortestPath(List<List<Integer>> G, int source, int destination) {
- List<Integer> dis = dijkstra(G, source);
- List<Integer> path = new ArrayList<>();
- if (dis.get(destination) == INF) {
- return path;
- }
- int current = destination;
- path.add(current);
- while (current != source) {
- int prev = -1;
- int minWeight = INF;
- for (int neighbor = 0; neighbor < G.size(); neighbor++) {
- int weight = G.get(neighbor).get(current);
- if (weight != 0 && dis.get(neighbor) + weight == dis.get(current)) {
- prev = neighbor;
- break;
- }
- }
- if (prev == -1) {
- return path;
- }
- path.add(prev);
- current = prev;
- }
- Collections.reverse(path);
- return path;
- }
- }
- GraphM:
- import java.util.ArrayList;
- public class GraphM {
- //用相邻矩阵实现无向图
- private ArrayList<Integer> V;//顶点
- private int E;//边数
- private int[][] matrix;//相邻矩阵
- /**
- * 初始化无向图
- * @param n 结点数
- */
- public GraphM(int n) {
- matrix = new int[n][n];
- V = new ArrayList<Integer>(n);
- }
- /**
- * 添加结点
- * @param vertex 结点值
- */
- public void insertVertex(Integer vertex){
- V.add(vertex);
- }
- /**
- * 插入边
- * @param v1 起点下标
- * @param v2 终点下标
- * @param weight 权值,这里1表示相邻,1000表示不相邻
- */
- public void insertEdge(int v1,int v2,int weight) {
- matrix[v1][v2] = weight;
- matrix[v2][v1] = weight;
- E++;//边数+1
- }
- /**
- * 获得v1->v2的权值
- * @param v1
- * @param v2
- * @return
- */
- public int getWeight(int v1,int v2){
- return matrix[v1][v2];
- }
- /**
- * 获得边的数量
- * @return
- */
- public int getEdgeNum(){
- return E;
- }
- /**
- * 获得结点数
- * @return
- */
- public int getVertexNum(){
- return V.size();
- }
- public int[] output(int row){
- return matrix[row];
- }
- }
- Cell:
- class Cell {
- private int x; // 格子的位置,在第几行
- private int y; // 第几列
- private int flag = Constants.NOTINTREE; // flag,标识格子是否已加入树中
- private Cell father = null; // 格子的父亲节点
- //1 代表 有边 1000 代表 无边
- private int right;
- private int down;
- public Cell(int xx, int yy) {
- x = xx;
- y = yy;
- }
- public int getX() {
- return x;
- }
- public void setX(int x) {
- this.x = x;
- }
- public int getY() {
- return y;
- }
- public void setY(int y) {
- this.y = y;
- }
- public int getFlag() {
- return flag;
- }
- public void setFlag(int flag) {
- this.flag = flag;
- }
- public Cell getFather() {
- return father;
- }
- public void setFather(Cell father) {
- this.father = father;
- }
- public int getRight() {
- return right;
- }
- public void setRight(int right) {
- this.right = right;
- }
- public int getDown() {
- return down;
- }
- public void setDown(int down) {
- this.down = down;
- }
- }
- Puzzle:
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Random;
- public class Puzzle {
- public GraphM graph;
- //down,right数组存储格子的上下左右四条边
- int[][] down = new int[Constants.GRID_SIZE][Constants.GRID_SIZE];
- int[][] right = new int[Constants.GRID_SIZE][Constants.GRID_SIZE];
- public void newPuzzle() {
- //1.数组全1000表示完整格子
- for (int i = 0; i < Constants.GRID_SIZE; i++) {
- for (int j = 0; j < Constants.GRID_SIZE; j++) {
- down[i][j] = Constants.INNEIGHBOURING;
- right[i][j] = Constants.INNEIGHBOURING;
- }
- }
- //2.随机down和right两个数组
- randomizeArray(down);
- randomizeArray(right);
- //3.创建抽象的全连接的图
- //定义图的所有顶点
- Integer[] vertexs = new Integer[Constants.GRID_SIZE * Constants.GRID_SIZE];
- for (int i = 0; i < vertexs.length; i++) {
- vertexs[i] = i;
- }
- //创建图
- graph = new GraphM(vertexs.length);
- //添加顶点到图中
- for (Integer vertex : vertexs) {
- graph.insertVertex(vertex);
- }
- //4.根据down和right两个数组添加边到图中
- for (int i = 0; i < Constants.GRID_SIZE - 1; i++) {
- for (int j = 0; j < Constants.GRID_SIZE; j++) {
- //对于down数组
- if(down[i][j] == Constants.INNEIGHBOURING){
- graph.insertEdge(i * Constants.GRID_SIZE + j, ( i + 1 ) * Constants.GRID_SIZE + j, Constants.INNEIGHBOURING);
- }else{
- graph.insertEdge(i * Constants.GRID_SIZE + j, ( i + 1 ) * Constants.GRID_SIZE + j, Constants.NEIGHBOURING);
- }
- }
- }
- for (int i = 0; i < Constants.GRID_SIZE; i++) {
- for (int j = 0; j < Constants.GRID_SIZE - 1; j++) {
- if(right[i][j] == Constants.INNEIGHBOURING){
- graph.insertEdge(i * Constants.GRID_SIZE + j, i * Constants.GRID_SIZE + j + 1, Constants.INNEIGHBOURING);
- }else{
- graph.insertEdge(i * Constants.GRID_SIZE + j, i * Constants.GRID_SIZE + j + 1, Constants.NEIGHBOURING);
- }
- }
- }
- }
- private static void randomizeArray(int[][] array) {
- Random random = new Random();
- int totalCells = Constants.GRID_SIZE * Constants.GRID_SIZE;
- int numZeroes = (int) (Constants.RANDOMPERCENTAGE * totalCells);
- while (numZeroes > 0) {
- int randomRow = random.nextInt(Constants.GRID_SIZE);
- int randomCol = random.nextInt(Constants.GRID_SIZE);
- if (array[randomRow][randomCol] != Constants.NEIGHBOURING) {
- array[randomRow][randomCol] = Constants.NEIGHBOURING;
- numZeroes--;
- }
- }
- }
- // 得到实现路径的方法
- public List<Integer> getPath(){
- // 构建图的邻接矩阵表示
- List<List<Integer>> adjacentMatrix = new ArrayList<>();
- // 导入图的链接矩阵
- for (int i = 0; i < Constants.GRID_SIZE * Constants.GRID_SIZE; i++) {
- int[] array = graph.output(i);
- List<Integer> row = new ArrayList<>();
- for (int value : array) {
- row.add(value);
- }
- adjacentMatrix.add(row);
- }
- // 调用方法
- DijkstraAlgorithm dijkstraAlgorithm = new DijkstraAlgorithm();
- int source = 0;
- List<Integer> Path = dijkstraAlgorithm.getShortestPath(adjacentMatrix, source, Constants.GRID_SIZE * Constants.GRID_SIZE - 1);
- return Path;
- }
- }
- Test:
- import javax.swing.*;
- import java.awt.*;
- import java.util.List;
- public class Test extends JPanel {
- public int padding = Constants.PADDING;
- public int width = (Constants.WIDTH - Constants.PADDING - Constants.PADDING) / Constants.GRID_SIZE;
- public Cell[][] maze;
- public Puzzle puzzle;
- private int numberFailtures = 0;
- private int numberTry = 0;
- Test() {
- maze = new Cell[Constants.GRID_SIZE][Constants.GRID_SIZE];
- puzzle = new Puzzle();
- puzzle.newPuzzle();
- for (int i = 0; i < 300; i++) {
- count();
- }
- System.out.println("迷宫成功率为" + (100 - ((double)numberFailtures / numberTry * 100)) + " %");
- }
- //这是个自动调用的方法,必须设置为public
- public void paintComponent(Graphics g) {
- super.paintComponent(g);
- // 画NUM*NUM条黑线
- for (int i = 0; i <= Constants.GRID_SIZE; i++) {
- g.drawLine(padding + i * width, padding, padding + i * width,
- padding + Constants.GRID_SIZE * width);
- }
- for (int j = 0; j <= Constants.GRID_SIZE; j++) {
- g.drawLine(padding, padding + j * width, padding + Constants.GRID_SIZE * width,
- padding + j * width);
- }
- // 使用背景色,在有路径的格子之间画边,把墙抹掉
- g.setColor(this.getBackground());
- //根据Puzzle中的数组进行抹边
- for (int i = 0; i < Constants.GRID_SIZE; i++) {
- for (int j = 0; j < Constants.GRID_SIZE; j++) {
- maze[i][j] = new Cell(i, j);
- if (puzzle.down[i][j] == Constants.NEIGHBOURING) {
- maze[i][j].setDown(Constants.NEIGHBOURING);
- }
- if (puzzle.down[i][j] == Constants.INNEIGHBOURING) {
- maze[i][j].setDown(Constants.INNEIGHBOURING);
- }
- if (puzzle.right[i][j] == Constants.NEIGHBOURING) {
- maze[i][j].setRight(Constants.NEIGHBOURING);
- }
- if (puzzle.right[i][j] == Constants.INNEIGHBOURING) {
- maze[i][j].setRight(Constants.INNEIGHBOURING);
- }
- }
- }
- for (int i = Constants.GRID_SIZE - 1; i >= 0; i--) {
- for (int j = Constants.GRID_SIZE - 1; j >= 0; j--) {
- if (maze[i][j].getRight() == Constants.NEIGHBOURING) {
- clearFence(i, j, i, j + 1, g);
- }
- if (maze[i][j].getDown() == Constants.NEIGHBOURING) {
- clearFence(i, j, i + 1, j, g);
- }
- }
- }
- // 画左上角的入口
- g.drawLine(padding, padding + 1, padding, padding + width - 1);
- int last = padding + Constants.GRID_SIZE * width;
- // 画右下角出口
- g.drawLine(last, last - 1, last, last - width + 1);
- // 画下边框
- g.setColor(Color.BLACK);
- g.drawLine(padding, last, last, last);
- // 画右边框
- g.drawLine(last, padding, last, last - width);
- // 画路径
- drawPath(g);
- }
- // 私有方法,目的是抹掉两个格子之间的边
- private void clearFence(int i, int j, int fx, int fy, Graphics g) {
- int sx = padding + ((j > fy ? j : fy) * width),
- sy = padding + ((i > fx ? i : fx) * width),
- dx = (i == fx ? sx : sx + width),
- dy = (i == fx ? sy + width : sy);
- if (sx != dx) {
- sx++;
- dx--;
- } else {
- sy++;
- dy--;
- }
- g.drawLine(sx, sy, dx, dy);
- }
- // 由格子的行数列数,得到格子中心点的像素XY坐标
- private int getCenterX(Cell p) {
- return padding + p.getY() * width + width / 2;
- }
- private int getCenterY(Cell p) {
- return padding + p.getX() * width + width / 2;
- }
- // 由序列数得到对应的行和列
- private int getRow(int num) {
- return (num - 1) / Constants.GRID_SIZE;
- }
- private int getCol(int num) {
- return num % Constants.GRID_SIZE;
- }
- private void drawPath(Graphics g) {
- g.setColor(Color.red);
- // 已经得到初始路径到最后路径的list,接下来对照相应的格子,再画出来就行
- List<Integer> path = puzzle.getPath();
- for (int i = 0; i < path.size() - 1; i++) {
- int first = path.get(i);
- int second = path.get(i + 1);
- g.drawLine(getCenterX(maze[getRow(first)][getCol(first)]), getCenterY(maze[getRow(first)][getCol(first)]), getCenterX(maze[getRow(second)][getCol(second)]), getCenterY(maze[getRow(second)][getCol(second)]));
- }
- }
- private void count() {
- //方便统计
- Puzzle p = new Puzzle();
- p.newPuzzle();
- List<Integer> path = p.getPath();
- numberTry++;
- if (path.isEmpty()) {
- numberFailtures++;
- }
- }
- public static void main(String[] args) {
- JFrame frame = new JFrame("Maze");
- JPanel test = new Test();
- //下面一行自动调用paintComponent方法
- frame.setContentPane(test);
- frame.setSize(Constants.WIDTH + Constants.PADDING, Constants.WIDTH + Constants.PADDING + Constants.PADDING);
- frame.setLocation(Constants.LX, Constants.LY);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setVisible(true);
- }
- }
- Constants:
- /**
- * 为当前应用中很多类需要使用的常量完成定义
- * 将逻辑上相关联的一组类所需要的常量定义在一个类中是可以借鉴的,这样易于维护。
- */
- public class Constants {
- /** 定义面板的每一行的单元格数 */
- public static final int GRID_SIZE = 40;
- /** 定义面板的大小 */
- public static final int WIDTH = 600;
- /** 定义面板的padding */
- public static final int PADDING = 10;
- /** 在树中 */
- public static final int INTREE = 1;
- /** 不在树中*/
- public static final int NOTINTREE = 0;
- /** 显示在屏幕上的位置 */
- public static final int LX = 450;
- public static final int LY = 100;
- /** 随机消除百分比 */
- public static final double RANDOMPERCENTAGE = 0.7;
- /** 权值,这里1表示相邻,1000表示不相邻 */
- public static final int NEIGHBOURING = 1;
- public static final int INNEIGHBOURING = 1000;
- }

被折叠的 条评论
为什么被折叠?



