%Copyright 2006, Adarsh Krishnamurthy (me.berkeley.edu/~adarsh) and Athulan Vijayaraghavan (me.berkeley.edu/~athulan)

function neigh_cells = neighbors2d(cell_no, maze_size)

a = mod(cell_no, maze_size);
if a==0
    a = maze_size;
end
b = ceil(cell_no/maze_size);

box_id = [a b];
    
neigh = [box_id(1)-1 box_id(2); box_id(1)+1 box_id(2); box_id(1) box_id(2)+1; box_id(1) box_id(2)-1];

[r, c] = find(neigh < 1);
neigh(r, :) = [];
[r, c] = find(neigh > maze_size);
neigh(r, :) = [];

for i = 1:size(neigh, 1)
    neigh_cells(i) = neigh(i, 1) + maze_size*(neigh(i, 2)-1);
end