forked from TamimEhsan/AlgorithmVisualizer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursiveMaze.js
More file actions
104 lines (100 loc) · 2.74 KB
/
Copy pathrecursiveMaze.js
File metadata and controls
104 lines (100 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
export function getMaze(board,row,col){
const pairs = [];
let newBoard = board.slice();
for( let i = 0;i <col;i++){
newBoard[0][i].isWall = true;
pairs.push({
xx:0,
yy:i
});
}
for( let i = 0;i <row;i++){
newBoard[i][col-1].isWall = true;
pairs.push({
xx:i,
yy:col-1
});
}
for( let i = col-1;i>=0;i-- ){
newBoard[row-1][i].isWall = true;
pairs.push({
xx:row-1,
yy:i
});
}
for(let i = row-1;i>=0;i--){
newBoard[i][0].isWall = true;
pairs.push({
xx:i,
yy:0
});
}
decideMaze(pairs,newBoard,1,row-2,1,col-2);
//console.log("here");
return pairs;
}
let val = 0;
function decideMaze(pairs,board,startRow,endRow,startCol,endCol) {
//console.log("count");
val++;
if( ((endRow-startRow) <=1) && ((endCol - startCol) <=1) ){
return;
}
if( (endCol - startCol) > (endRow - startRow) ){
recursiveMazeVertical(pairs,board,startRow,endRow,startCol,endCol);
} else{
recursiveMazeHorizontal(pairs,board,startRow,endRow,startCol,endCol);
}
}
function recursiveMazeVertical(pairs,board,startRow,endRow,startCol,endCol){
let mid = Math.floor((endCol+startCol)/2);
let random = Math.floor(Math.random() * (endRow-startRow+1)) + startRow;
//console.log( "row ",random," ",startRow," ",endRow );
let start = startRow;
if( !board[startRow-1][mid].isWall ){
random = start;
start++;
}
let end = endRow;
if( !board[endRow+1][mid].isWall ){
random = end;
end--;
}
for(let i = start;i<=end;i++){
if( i!==random ){
board[i][mid].isWall = true;
pairs.push({
xx:i,
yy:mid
});
}
}
decideMaze(pairs,board,startRow,endRow,startCol,mid-1);
decideMaze(pairs,board,startRow,endRow,mid+1,endCol);
}
function recursiveMazeHorizontal(pairs,board,startRow,endRow,startCol,endCol){
let mid = Math.floor((endRow+startRow)/2);
// console.log("mid: ",mid);
let random = Math.floor(Math.random() * (endCol-startCol+1)) + startCol;
let start = startCol;
if( !board[mid][startCol-1].isWall ){
random = start;
start++;
}
let end = endCol;
if( !board[mid][endCol+1].isWall ){
random = end;
end--;
}
for(let i = start;i<=end;i++){
if( i!==random ){
board[mid][i].isWall = true;
pairs.push({
xx:mid,
yy:i
});
}
}
decideMaze(pairs,board,startRow,mid-1,startCol,endCol);
decideMaze(pairs,board,mid+1,endRow,startCol,endCol);
}