본문 바로가기
Python/알고리즘

[python] 스택 응용 : 미로 문제

by 덤더리덤떰 2023. 11. 20.
class Pos():
    def __init__(self, row,col):
        self.row = row
        self.col= col

class Stack():
    def __init__(self,size):
        self.data=[]
        self.top=-1
        self.size=size

    def push(self, item):
        self.data.append(item)
        self.top+=1
    
    def pop(self):
        
        self.top-=1
        return self.data.pop()
    
    def peek(self):
        return self.data[self.top]
    
    def isEmpty(self):
        return self.top==-1
    
    def isFull(self):
        return self.top == self.size-1
    
    def PrintStack(self):
        for i in range(5,self.top,-1):
            print('|     |')
        
        for i in range(self.top,-1,-1):
            print(f'|({self.data[i].row},{self.data[i].col})|')

        print('-------')


def PrintMaze(maze,here):
    print()
    for i in range(6):
        for j in range(6):
            
            if(i==here.row and j==here.col):
                print('m', end=" ")
            else:
                print(maze[i][j], end=" ")
        print()


def PushStack(stack,row,col,maze):
    if(row<0 or col <0 or row >=6  or col>=6):
        return
    if(maze[row][col]=='1' or maze[row][col]=='.'):
        return
    elif(maze[row][col]=='0' or maze[row][col]=='x'):
        here = Pos(row,col)
        stack.push(here)
        stack.PrintStack()
        PrintMaze(maze,here)



def FindRoot(maze):
    stack = Stack(20)
    row=1
    col=0
    
    while(maze[row][col]!='x'):
        PrintMaze(maze,Pos(row,col))
        maze[row][col]='.'
        
        PushStack(stack, row-1,col,maze)
        PushStack(stack, row+1,col,maze)
        PushStack(stack, row,col-1,maze)
        PushStack(stack, row,col+1,maze)

        if(stack.isEmpty()):
            return '실패'
        else:
            now = stack.pop()
            row=now.row
            col = now.col
    
    stack.PrintStack()
    print("성공")
        



def main():
    maze=[['1','1','1','1','1','1'],
		['e','0','1','0','0','1'],
		['1','0','0','0','1','1'],
		['1','0','1','0','1','1'],
		['1','0','1','0','0','x'],
		['1','1','1','1','1','1']]

    FindRoot(maze)



if __name__=="__main__":
    main()