250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[python/파이썬] 코딩테스트에서 많이 나오는 X,S,G,* 이용한 미로 만들기 maze.py 본문

Python/고전 컴퓨터 알고리즘

[python/파이썬] 코딩테스트에서 많이 나오는 X,S,G,* 이용한 미로 만들기 maze.py

polarcompass 2022. 4. 19. 18:03
728x90
from enum import Enum
from typing import List, NamedTuple, Callable, Optional
import random
from math import sqrt
from urllib.parse import MAX_CACHE_SIZE
# from generic_search import dfs, bfs, node_to_path, astar, Node

class Cell(str, Enum):
    EMPTY = " "
    BLOCKED = "X"
    START = "S"
    GOAL = "G"
    PATH = "*"

class MazeLocation(NamedTuple):
    row: int
    column: int

class Maze:
    def __init__(self, rows: int = 10
                ,columns: int = 10
                ,sparseness: float = 0.2
                ,start: MazeLocation = MazeLocation(0,0)
                ,goal: MazeLocation = MazeLocation(9,9)):
        
        # 기본 인스턴스 변수 초기화
        self._rows: int = rows
        self._columns: int = columns
        self.start: MazeLocation = start
        self.goal: MazeLocation = goal
        
        # 격자를 빈 공간으로 채운다.
        self._grid: List[List[Cell]] = [[Cell.EMPTY for c in range(columns)] for r in range(rows)]
        
        # 격자에 막힌 공간을 무작위로 채운다.
        self._randomly_fill(rows, columns, sparseness)
        
        # 시작 위치와 목표 위치를 설정한다.
        self._grid[start.row][start.column] = Cell.START
        self._grid[goal.row][goal.column] = Cell.GOAL
        
    def _randomly_fill(self, rows: int, columns: int, sparseness: float):
        for row in range(rows):
            for column in range(columns):
                if random.uniform(0, 1.0) < sparseness: # 무작위수가 0.2보다 작으면 X로 막는다.
                    self._grid[row][column] = Cell.BLOCKED

    # 미로 출력
    def __str__(self):
        output = ""
        for row in self._grid:
            output += "".join([c.value for c in row]) + "\n"
        return output
    
maze = Maze()
print(maze)

 

결과값:
기본적으로 무작위로 생성됨.
SX       X
  X  XXXX 
XX   X  X 
          
X   X  X  
        X 
      X   
 XX X   XX
    X XX  
  X    X G

 

728x90