# L-12 MCS 275 Mon 8 Feb 2010 : find a path through a maze from numpy import * import random def PrintMaze(M): """ Writes the maze to screen, spaces if free, # is blocked. """ s = ' ' for j in range(0,M.shape[1]): s = s + '%3d' % j print s for i in range(0,M.shape[0]): s = '%3d :' % i for j in range(0,M.shape[1]): if M[i,j] == 0: s = s + ' ' elif M[i,j] == -1: s = s + '###' else: s = s + '%3d' % M[i,j] print s def RandomMaze(rows,cols): """ Returns a random integer matrix with dimensions in rows and cols, indicating free positions with 0 and occupied positions with -1. Free positions are at [0,0] and [rows-1,cols-1]. """ M = zeros((rows,cols),int) for i in range(0,rows): for j in range(0,cols): M[i,j] = random.randint(-1,0) M[0,0] = 0 M[rows-1,cols-1] = 0 return M def MakeMaze(rows,cols): """ Returns a random integer matrix with dimensions in rows and cols, indicating free positions with 0 and occupied positions with -1. Free positions are at [0,0] and [rows-1,cols-1]. """ M = RandomMaze(rows,cols) while True: PrintMaze(M) i = input('to change, give i (-1 if not) : ') if i < 0: break j = input('to change, give j (-1 if not) : ') if j < 0: break if M[i,j] == -1: M[i,j] = 0 else: M[i,j] = -1 return M def Search(M,i,j,k): """ Search a path upwards, starting at (i,j)-th position. Markes visited tiles with increasing numbers. Returns M and a boolean indicating the arrival. """ M[i,j] = k if i == M.shape[0] - 1 and j == M.shape[1] - 1: return (M,True) else: b = False if i < M.shape[0]-1: if M[i+1,j] == 0: (M,b) = Search(M,i+1,j,k+1) if not b and j < M.shape[1]-1: if M[i,j+1] == 0: (M,b) = Search(M,i,j+1,k+1) if not b and i > 0: if M[i-1,j] == 0: (M,b) = Search(M,i-1,j,k+1) if not b and j > 0: if M[i,j-1] == 0: (M,b) = Search(M,i,j-1,k+1) return (M,b) def main(): """ prompts for dimension of a grid """ r = input('give #rows : ') c = input('give #columns : ') M = MakeMaze(r,c) PrintMaze(M) (M,b) = Search(M,0,0,1) if b: print 'path found' else: print 'no path found' PrintMaze(M) main()