-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12.ts
112 lines (100 loc) · 2.41 KB
/
12.ts
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
105
106
107
108
109
110
111
112
import Solution from "./solution.ts";
class Point {
#value: string;
previous?: Point;
distance = Number.MAX_SAFE_INTEGER;
#x: number;
#y: number;
constructor(value: string, x: number, y: number) {
this.#value = value;
if (value === "S") {
this.distance = 0;
}
this.#x = x;
this.#y = y;
}
compare(p: Point) {
return this.value.charCodeAt(0) - p.value.charCodeAt(0);
}
newPath(p: Point) {
if (this.distance > p.distance + 1) {
this.distance = p.distance + 1;
this.previous = p;
}
}
get value() {
if (this.#value === "S") return "a";
if (this.#value === "E") return "z";
return this.#value;
}
get x() {
return this.#x;
}
get y() {
return this.#y;
}
get isEnd() {
return this.#value === "E";
}
get isStart() {
return this.#value === "a";
}
}
const task = new Solution(
(map: Point[][]) => {
const distance = map.flat(2).sort((a, b) => b.distance - a.distance);
while (distance.length > 0) {
const point = distance.pop()!;
for (const p of [
map[point.y - 1]?.[point.x],
map[point.y + 1]?.[point.x],
map[point.y]?.[point.x - 1],
map[point.y]?.[point.x + 1],
]) {
if (p && distance.includes(p) && point.compare(p) > -2) {
p.newPath(point);
}
}
if (point.isEnd) {
return point.distance;
}
distance.sort((a, b) => b.distance - a.distance);
}
return 0;
},
(map: Point[][]) => {
const distance = map
.flat(2)
.map((p) => {
if (p.distance === 0) p.distance = Number.MAX_SAFE_INTEGER;
if (p.isEnd) p.distance = 0;
return p;
})
.sort((a, b) => b.distance - a.distance);
while (distance.length > 0) {
const point = distance.pop()!;
for (const p of [
map[point.y - 1]?.[point.x],
map[point.y + 1]?.[point.x],
map[point.y]?.[point.x - 1],
map[point.y]?.[point.x + 1],
]) {
if (p && distance.includes(p) && point.compare(p) < 2) {
p.newPath(point);
}
}
if (point.isStart) {
return point.distance;
}
distance.sort((a, b) => b.distance - a.distance);
}
return 0;
},
{
transform: (a, y) => a.split("").map((s, x) => new Point(s, x, y)),
sep: "\n",
},
);
task.expect(31, 29);
if (import.meta.main) await task.execute();
export default task;