-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathFindPath.html
More file actions
80 lines (73 loc) · 1.81 KB
/
FindPath.html
File metadata and controls
80 lines (73 loc) · 1.81 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// 寻路算法
class FindPath {
constructor(arr) {
this.visited = new Array(arr.length).fill(false);
this.from = new Array(arr.length).fill(-1);
for (let i = 0; i < this.visited.length; i++) {
if (!this.visited[i]) {
this.dfs(arr, i);
}
}
// console.log(this.from)
}
dfs(arr, v) {
this.visited[v] = true;
for (let i = 0; i < arr[v].length; i++) {
if (!this.visited[arr[v][i]]) {
this.from[arr[v][i]] = v;
this.dfs(arr, arr[v][i])
}
}
}
hasPath(w) {
return this.visited[w]
}
find(w, vec) {
let stack = [],
p = w;
while (p !== -1) {
stack.push(p);
p = this.from[p];
}
let temp;
while (stack.length) {
temp = stack.pop();
vec.push(temp);
}
}
showPath(w) {
let vector = [],
path = '';
this.find(w, vector);
console.log(vector)
for (let i = 0; i < vector.length; i++) {
if (i === vector.length - 1) {
path += vector[i]
} else {
path += `${vector[i]} -> `
}
}
console.log(path)
}
}
let graph = [
[1, 2, 5, 6],
[0],
[0],
[4, 5],
[3, 5, 6],
[0, 3, 4],
[0, 4]
]
new FindPath(graph).showPath(6)
</script>
</body>
</html>