%Copyright 2006, Adarsh Krishnamurthy (me.berkeley.edu/~adarsh) and Athulan Vijayaraghavan (me.berkeley.edu/~athulan) clc; clear all; %recursive backtracker tic %size of the maze - only square maze_size = 20; n_cells = maze_size*maze_size; %listing all the cells with a uid in an array k = 1; for i = 1:maze_size for j = 1:maze_size corners = corner_pts([j i])'; cells(k, :) = [k corners(:)']; k = k + 1; end end %listing all the edges with a uid in an array edges = []; k = 1; for i = 1:maze_size-1 for j = 1:maze_size edges(k, :) = [k i j-1 i j]; edges(k+1, :) = [k+1 j-1 i j i]; k = k + 2; end end %list all the edges for the cells for i = 1:size(cells, 1) cell_col = [cells(i,2) cells(i,3); cells(i,4) cells(i,5); cells(i,6) cells(i,7); cells(i,8) cells(i,9)]; k = 2; cell_edges(i, 1) = i; for j = 1:size(edges, 1) edge_col = [edges(j,2) edges(j,3); edges(j,4) edges(j,5)]; if (ismember(edge_col, cell_col, 'rows')==[1;1]) cell_edges(i, k) = j; k = k+1; end end end %initialize the cell stack stack = []; %choose a random cell to begin with r = ceil(length(cells)*(rand)); stack(1) = r; visited = stack; cells(r, :) = []; ctr = 1; while length(stack)>0 stack; visited; current_cell = stack(end); current_neighbors = neighbors2d(current_cell(1), maze_size); for i = 1:length(current_neighbors) if ismember(current_neighbors(i), visited) current_neighbors(i) = 0; end end current_neighbors(find(current_neighbors==0))=[]; if length(current_neighbors)==0 stack(end) = []; elseif length(current_neighbors>0) r = ceil(length(current_neighbors)*(rand)); chosen_neighbor = current_neighbors(r); common_edge = intersect(cell_edges(chosen_neighbor, 2:5), cell_edges(current_cell, 2:5)); common_edge(find(common_edge==0))=[]; edges(find(edges(:, 1)==common_edge), :)=[]; stack(end+1) = chosen_neighbor; visited(end+1) = chosen_neighbor; end ctr = ctr + 1 end show_maze(maze_size, edges); ctr