zoukankan      html  css  js  c++  java
  • python生成迷宫

    # -*- coding: utf-8 -*-
    """
    Created on Sat Mar  8 23:52:39 2021
    
    @author: mengxin
    """
    
    import random
    import numpy as np
    
    row = 15
    cul = 15
    if row % 2 == 0:
        row = row + 1
    if cul % 2 == 0:
        cul = cul + 1
    def creator(row, cul):
      a = np.ones((row + 2, cul + 2), dtype = int)
      b = np.zeros(a.shape, dtype = bool)
      return a, b
    
    t_map, t_b = creator(row, cul)
    
    while(True):
      a = (random.randint(0, row + 1), random.randint(0, cul + 1))
      if a[0] % 2 == 1 and a[1] % 2 == 1:
        break
    
    allst = []
    allst.append(a)
    while(allst):
      b = allst.pop(random.randint(0, len(allst) - 1))
      t_map[b[0]][b[1]] = 0
      arnd = []
      if b[0] > 1 and b[0] < row:
        if t_map[b[0] - 2][b[1]] == 0:
          arnd.append([b[0] - 2, b[1]])
        else:
          allst.append((b[0] - 2, b[1]))
        if t_map[b[0] + 2][b[1]] == 0:
          arnd.append([b[0] + 2, b[1]])
        else:
          allst.append((b[0] + 2, b[1]))
      elif b[0] == 1:
        if t_map[b[0] + 2][b[1]] == 0:
          arnd.append([b[0] + 2, b[1]])
        else:
          allst.append((b[0] + 2, b[1]))
      elif b[0] == row:
        if t_map[b[0] - 2][b[1]] == 0:
          arnd.append([b[0] - 2, b[1]])
        else:
          allst.append((b[0] - 2, b[1]))
      if b[1] > 1 and b[1] < cul:
        if t_map[b[0]][b[1] - 2] == 0:
          arnd.append([b[0], b[1] - 2])
        else:
          allst.append((b[0], b[1] - 2))
        if t_map[b[0]][b[1] + 2] == 0:
          arnd.append([b[0], b[1] + 2])
        else:
          allst.append((b[0], b[1] + 2))
      elif b[1] == 1:
        if t_map[b[0]][b[1] + 2] == 0:
          arnd.append([b[0], b[1] + 2])
        else:
          allst.append((b[0], b[1] + 2))
      elif b[1] == cul:
        if t_map[b[0]][b[1] - 2] == 0:
          arnd.append([b[0], b[1] - 2])
        else:
          allst.append((b[0], b[1] - 2))
      allst = list(set(allst))
      if arnd:
        c = arnd.pop(random.randint(0, len(arnd) - 1))
        if b[0] == c[0]:
            c[1] = (b[1] + c[1]) // 2
        elif b[1] == c[1]:
            c[0] = (b[0] + c[0]) // 2
        t_map[c[0]][c[1]] = 0
    
    for i in range(len(t_map)):
        s = ''
        for j in range(len(t_map[i])):
            if t_map[i][j] == 0:
                s += '0'
            else:
                s += '1'
        print(s)

    其中0为路径,1为墙体。

  • 相关阅读:
    关于JDK中自带的类加载器
    关于Spring框架
    关于Java JUC
    数据库-数据添加与删除-视图-索引-存储过程
    数据库-查询练习
    数据库-数据类型-数据库创建表的 约束以及 DDL操作
    数据库-多表连接查询
    数据库笔记整理-数据库概述-三大范式及数据库基本命令
    JAVA笔记整理-JAVA网络编程-TCP/UDP传输
    JAVA笔记整理-线程二
  • 原文地址:https://www.cnblogs.com/mengxinteriri/p/14509061.html
Copyright © 2011-2022 走看看