class Node {
constructor(value =
null
, next_element =
null
) {
this
.val = value;
this
.next = next_element;
}
}
class Stack {
constructor() {
this
.head =
null
;
this
.length = 0;
}
insert(data) {
this
.head =
new
Node(data,
this
.head);
this
.length += 1;
}
pop() {
if
(
this
.length === 0) {
return
null
;
}
else
{
let returned =
this
.head.val;
this
.head =
this
.head.next;
this
.length -= 1;
return
returned;
}
}
not_empty() {
return
Boolean(
this
.length);
}
top() {
return
this
.head.val;
}
}
function
random_maze_generator(r, c, P0, Pf) {
const ROWS = r;
const COLS = c;
const maze = [...Array(ROWS)].map(() => Array(COLS).fill(0));
const seen = [...Array(ROWS)].map(() => Array(COLS).fill(
false
));
const previous = [...Array(ROWS)].map(() => Array(COLS).fill([-1, -1]));
const S = [];
S.push(P0);
while
(S.length > 0) {
const [x, y] = S.pop();
seen[x][y] =
true
;
if
(x + 1 < ROWS && maze[x + 1][y] === 1 && !isEqual(previous[x][y], [x + 1, y]))
continue
;
if
(x > 0 && maze[x - 1][y] === 1 && !isEqual(previous[x][y], [x - 1, y]))
continue
;
if
(y + 1 < COLS && maze[x][y + 1] === 1 && !isEqual(previous[x][y], [x, y + 1]))
continue
;
if
(y > 0 && maze[x][y - 1] === 1 && !isEqual(previous[x][y], [x, y - 1]))
continue
;
maze[x][y] = 1;
const to_stack = [];
if
(x + 1 < ROWS && !seen[x + 1][y]) {
seen[x + 1][y] =
true
;
to_stack.push([x + 1, y]);
previous[x + 1][y] = [x, y];
}
if
(x > 0 && !seen[x - 1][y]) {
seen[x - 1][y] =
true
;
to_stack.push([x - 1, y]);
previous[x - 1][y] = [x, y];
}
if
(y + 1 < COLS && !seen[x][y + 1]) {
seen[x][y + 1] =
true
;
to_stack.push([x, y + 1]);
previous[x][y + 1] = [x, y];
}
if
(y > 0 && !seen[x][y - 1]) {
seen[x][y - 1] =
true
;
to_stack.push([x, y - 1]);
previous[x][y - 1] = [x, y];
}
let pf_flag =
false
;
while
(to_stack.length > 0) {
const index = Math.floor(Math.random() * to_stack.length);
const neighbour = to_stack.splice(index, 1)[0];
if
(isEqual(neighbour, Pf)) {
pf_flag =
true
;
}
else
{
S.push(neighbour);
}
}
if
(pf_flag) {
S.push(Pf);
}
}
const [x0, y0] = P0;
const [xf, yf] = Pf;
maze[x0][y0] = 2;
maze[xf][yf] = 3;
return
maze;
}
function
isEqual(arr1, arr2) {
return
arr1[0] === arr2[0] && arr1[1] === arr2[1];
}
const N = 5;
const M = 5;
const P0 = [0, 0];
const P1 = [4, 4];
const maze = random_maze_generator(N, M, P0, P1);
for
(const line of maze) {
console.log(line);
}