Advertisement
colinm86

Untitled

Oct 16th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. from stack import Stack
  2.  
  3.  
  4. def getmaze():
  5.     '''returns maze text file'''
  6.     file = open('maze.txt','r')
  7.     x = file.read()
  8.     return x.split('\n')  
  9.  
  10. def str_list(string):
  11.     '''converts string to list'''
  12.     return list(string)
  13.  
  14. def list_str(lst):
  15.     '''converts list to string'''
  16.     return ''.join(lst)
  17.  
  18. def update_maze(maze,row,col):
  19.     '''adds trail on maze of previous positions'''
  20.     string_lst = str_list(maze[row])
  21.     string_lst[col] = '.'
  22.     maze[row] = list_str(string_lst)
  23.  
  24. def run_maze(maze):
  25.     '''main maze run function, returns solution'''
  26.     stack = Stack()
  27.     numrows = len(maze)
  28.     numcols = len(maze[0])
  29.     curr_row,curr_col = 1,0
  30.     postions = ((-1,0),(0,1),(1,0),(0,-1))
  31.     found = False
  32.  
  33.     while not found:
  34.         for i in range(0,4):
  35.             searchrow,searchrcol = curr_row + postions[i][0], curr_col + postions[i][1]
  36.             if searchrow in range(numrows) and searchrcol in range(numcols):
  37.                 if maze[searchrow][searchrcol] == '0':
  38.                     stack.push([searchrow,searchrcol])
  39.                 elif maze[searchrow][searchrcol] == 'X':
  40.                     stack.push([searchrow,searchrcol])
  41.                     found = True
  42.         update_maze(maze,curr_row,curr_col)
  43.         current_pos = stack.pop()
  44.         curr_row,curr_col = current_pos[0], current_pos[1]
  45.  
  46.     return current_pos
  47.  
  48. def main():
  49.     maze = getmaze()
  50.     solution = run_maze(maze)
  51.     print(f'Solution found{solution}')
  52.  
  53. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement