-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearchGraph.ts
More file actions
31 lines (30 loc) · 809 Bytes
/
searchGraph.ts
File metadata and controls
31 lines (30 loc) · 809 Bytes
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
const graph = {
1: [2, 3, 4],
2: [1, 5],
3: [1, 5],
4: [1, 6],
5: [2, 3, 7],
6: [4, 7],
7: [5, 6],
};
function searchGraph(start: number) {
let result: number[] = [start];
const map: Map<number, number> = new Map();
map.set(start, start);
let needToGetNeighbors = graph[start] as number[];
let i = 0;
while (i < needToGetNeighbors.length) {
const neighbor = needToGetNeighbors[i];
if (map.get(neighbor) === undefined) {
result.push(neighbor);
map.set(neighbor, neighbor);
}
const newNeighbors = graph[neighbor] as number[];
const newNeedToGetNeighbors = newNeighbors.filter(
(newNeighbor) => map.get(newNeighbor) === undefined
);
needToGetNeighbors = needToGetNeighbors.concat(newNeedToGetNeighbors);
i += 1;
}
return result;
}