-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixPot.js
More file actions
59 lines (56 loc) · 1.71 KB
/
MatrixPot.js
File metadata and controls
59 lines (56 loc) · 1.71 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
const myMaze = [
[1, 0, 0, 1, 1],
[1, 1, 0, 1, 1],
[1, 0, 0, 1, 1],
[1, 0, 1, 1, 0],
[1, 0, 0, 0, 0]
]
function flowerPot(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
for (let j = 0; j < cols; j++) {
if (matrix[0][j] < 1) {
matrix[0][j] = 1;
let count = 1, pos = [{ row: 0, col: j }];
while (count) {
console.log(pos);
const newPos = [];
for (let i = 0; i < count; i++) {
if (pos[i].row == rows - 1) return true;
if (pos[i].row < rows - 1) {
if (matrix[pos[i].row + 1][pos[i].col] == 0) {
newPos.push({ row: pos[i].row + 1, col: pos[i].col });
matrix[pos[i].row + 1][pos[i].col] = 1;
}
};
if (pos[i].row > 0) {
if (matrix[pos[i].row - 1][pos[i].col] == 0) {
newPos.push({ row: pos[i].row - 1, col: pos[i].col });
matrix[pos[i].row - 1][pos[i].col] = 1;
}
};
if (pos[i].col < cols - 1) {
if (matrix[pos[i].row][pos[i].col + 1] == 0) {
newPos.push({ row: pos[i].row, col: pos[i].col + 1 });
matrix[pos[i].row][pos[i].col + 1] = 1
}
}
if (pos[i].col > 0) {
if (matrix[pos[i].row][pos[i].col - 1] == 0) {
newPos.push({ row: pos[i].row, col: pos[i].col - 1 });
matrix[pos[i].row][pos[i].col - 1] = 1;
}
}
}
pos = newPos;
count = pos.length;
}
}
}
return false;
}
function matrixPot(matrix) {
const result = flowerPot(matrix);
console.log(result);
}
matrixPot(myMaze);