-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdepth-first-search.ts
74 lines (59 loc) · 1.59 KB
/
depth-first-search.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
import { GraphType, Graph } from "graph";
import { canVisitedVertex, restorePath } from "./utils";
import { AlgoritmController } from "./controller";
export function depthFirstSearch(
startIndex: number,
endIndex: number,
graph: GraphType,
graphControll: Graph
) {
let prevIndex = null;
let isWork = true;
const aInfo = new AlgoritmController(startIndex, endIndex);
const stack = [startIndex];
const visited = [startIndex];
const path: { [key: string]: number } = {};
while (isWork && stack.length > 0) {
const currentIndex = stack.shift();
if (currentIndex === undefined) {
isWork = false;
break;
}
aInfo.addVertex(
{
vertex: currentIndex,
siblings: graph[currentIndex].siblings,
},
prevIndex
);
for (let i = 0; i < graph[currentIndex].siblings.length; i++) {
const sibling = graph[currentIndex].siblings[i];
if (!sibling) {
isWork = false;
break;
}
const vertex = graphControll.getVertexByIndex(sibling.vertex);
if (
vertex &&
!visited.includes(sibling.vertex) &&
canVisitedVertex(vertex)
) {
stack.unshift(sibling.vertex);
visited.push(sibling.vertex);
path[sibling.vertex] = currentIndex;
aInfo.increment();
}
if (sibling.vertex === endIndex) {
isWork = false;
break;
}
}
prevIndex = currentIndex;
}
const result = aInfo.getAlgotitmResult();
const restoredPath = restorePath(endIndex, startIndex, path);
return {
...result,
path: restoredPath,
};
}