-
Notifications
You must be signed in to change notification settings - Fork 1
/
bfs.ts
47 lines (42 loc) · 1011 Bytes
/
bfs.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
import Queue from '@/algs4/1-3/node-queue'
import Graph from './graph'
export default class BreadthFirstPaths {
private marked: boolean[]
private edgeTo: number[]
private s: number
constructor(G: Graph, s: number) {
this.marked = []
this.edgeTo = []
this.s = s
this.bfs(G, s)
}
private bfs(G: Graph, s: number) {
const queue = new Queue<number>()
this.marked[s] = true
queue.enqueue(s)
while (!queue.isEmpty()) {
const v = queue.dequeue()
const adj = G.getAdj(v)
while (adj.hasNext()) {
const w = adj.next()
if (!this.marked[w]) {
this.edgeTo[w] = v
this.marked[w] = true
queue.enqueue(w)
}
}
}
}
hasPathTo(v: number): boolean {
return this.marked[v]
}
pathTo(v: number): number[] {
if (!this.hasPathTo(v)) return null
const path = []
for (let x = v; x !== this.s; x = this.edgeTo[x]) {
path.push(x)
}
path.push(this.s)
return path
}
}