I have code here with a maze that uses a recursive function to solve the maze and then prints out all the coordinates from start to exit.
% clear workspace
clearvars;clear global MAZE ROWLIMIT COLLIMIT ROWEND COLEND% maze, its size, and endpoint must be global
global MAZE ROWLIMIT COLLIMIT ROWEND COLEND% maze
MAZE(1,:) = '############'; MAZE(2,:) = '# # #'; MAZE(3,:) = ' # # #### #'; MAZE(4,:) = '### # # #'; MAZE(5,:) = '# ### # '; MAZE(6,:) = '#### # # # #'; MAZE(7,:) = '# # # # # #'; MAZE(8,:) = '## # # # # #'; MAZE(9,:) = '# # #';MAZE(10,:) = '###### ### #';MAZE(11,:) = '# # #';MAZE(12,:) = '############';% constants & initial values
ROWLIMIT = 12;COLLIMIT = 12;rowbegin = 3;colbegin = 1;ROWEND = 5;COLEND = 12;% solve the maze -- (0,0) is a dummy "previous" value
isPathToExit(0, 0, rowbegin, colbegin);
This is the code I written so far for the recursive function 'isPathToExit':
function success = isPathToExit(previous_row, previous_col, current_row, current_col)% Finds a path from entrance to exit through the maze
% base case
global MAZE ROWLIMIT COLLIMIT ROWEND COLENDif current_row == ROWEND && current_col == COLEND disp(sprintf('(%i, %i)', current_row, current_col)); success = true; return;else success = false;end% recursion
if current_row+1 ~= previous_row && MAZE(current_row+1, current_col) ~= '#' && current_row+1 ~= ROWLIMIT && current_row ~= 0 success = isPathToExit(current_row, current_col, current_row+1, current_col); if success disp(sprintf('(%i, %i)', current_row+1, current_col)); return; endendif current_row-1 ~= previous_row && MAZE(current_row-1, current_col) ~= '#' && current_row-1 ~= ROWLIMIT && current_row ~= 0 success = isPathToExit(current_row, current_col, current_row-1, current_col); if success disp(sprintf('(%i, %i)', current_row-1, current_col)); return; endendif current_col+1 ~= previous_col && MAZE(current_row, current_col+1) ~= '#' && current_col+1 ~= COLLIMIT && current_col ~= 0 success = isPathToExit(current_row, current_col, current_row, current_col+1); if success disp(sprintf('(%i, %i)', current_row, current_col+1)); return; endendif current_col-1 ~= previous_col && MAZE(current_row, current_col-1) ~= '#' && current_col-1 ~= COLLIMIT && current_col ~= 0 success = isPathToExit(current_row, current_col, current_row, current_col+1); if success disp(sprintf('(%i, %i)', current_row, current_col-1)); return; endend
When I run it, it displays the points up to a wall of the maze and stops. I need it display the points from start to exit.
Best Answer