实现图的宽度优先遍历_Python可视化优先算法:走迷宫

点击上方“简说Python”,选择“置顶/星标公众号”

福利干货,第一时间送达!

d559af3071bc3f5cedd1649a1681f3af.gif

【作者简介】

  冒绿光的盒子,公众号投稿作者,个人简书主页:https://www.jianshu.com/u/cbacf40d927f。

走迷宫

显示迷宫

迷宫生成等等再提,先看一下迷宫的读取和显示。

469e41efd3eccc95743a3d93a44adee8.png

第一行是行数和列数,代表有101行101列,这个迷宫后面可以使用最小生成树生成。读进一个迷宫:

public class MazeData { private char[][] maze;private int N, M;public static final char ROAD = '#';public static final char WALL = ' ';public MazeData(String fileName) { if (fileName == null) { throw new IllegalArgumentException("filename can't be null!");
        }
        Scanner scanner = null;try {
            File file = new File(fileName);if (!file.exists()) { throw new IllegalArgumentException("File is not exist!");
            }
            FileInputStream fileInputStream = new FileInputStream(file);
            scanner = new Scanner(new BufferedInputStream(fileInputStream), "UTF-8");
            String nm = scanner.nextLine();
            String[] nmC = nm.trim().split("\\s+");
            N = Integer.parseInt(nmC[0]);
            M = Integer.parseInt(nmC[1]);
            maze = new char[N][M];for (int i = 0; i                 String line = scanner.nextLine();if (line.length() != M) { throw new IllegalArgumentException("Message of file is not completed!");
                }for (int j = 0; j                     maze[i][j] = line.charAt(j);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally { if (scanner != null) {
                scanner.close();
            }
        }
    }public char getMaze(int i, int j) { if (!inArea(i, j)) { throw new IllegalArgumentException("out of range!");
        }return maze[i][j];
    }public boolean inArea(int x, int y) { return x >= 0 && x = 0 && y     }public int N() { return N;
    }public int M() { return M;
    }
}

使用File来获得当前文件,如果没有就要抛出异常。scanner获得输入流之后可以通过读取下一行获得每一行的内容,列数在前面已经提到了,所以要检查每一行是不是M列,不是就没得读了。#就是墙,空格是路,可以设置两个静态变量表示。同时还需要各种辅助函数,比如是否是在整区域里面的,返回当前区域的值等等。然后就是显示函数了:

            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.getMaze(i, j) == MazeData.ROAD){
                        AlgorithmHelper.setColor(graphics2D, AlgorithmHelper.LightBlue);
                    }else {
                        AlgorithmHelper.setColor(graphics2D, AlgorithmHelper.White);
                    }
                    AlgorithmHelper.fillRectangle(graphics2D, j * w, i * h, w, h);
     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值