-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathNode.js
55 lines (45 loc) · 1.2 KB
/
Node.js
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
export class Node {
constructor(val, neighbors) {
this.val = val === undefined ? 0 : val
this.neighbors = neighbors === undefined ? [] : neighbors
}
static parse(edges) {
const nodeMap = new Map()
// 创建节点
const getNode = (val) => {
if (!nodeMap.has(val)) {
const newNode = new Node(val)
nodeMap.set(val, newNode)
}
return nodeMap.get(val)
}
// 连接节点
edges.forEach((neighbors, index) => {
const val = index + 1
const currentNode = getNode(val)
neighbors.forEach((neighborVal) => {
const neighborNode = getNode(neighborVal)
currentNode.neighbors.push(neighborNode)
})
})
return nodeMap.size > 0 ? nodeMap.values().next().value : null
}
static toArray(node) {
if (!node)
return []
const visited = new Set()
const result = []
const dfs = (currentNode) => {
if (visited.has(currentNode.val))
return
const { neighbors, val } = currentNode
visited.add(val)
result.push(neighbors.map(({ val }) => val))
currentNode.neighbors.forEach((neighbor) => {
dfs(neighbor)
})
}
dfs(node)
return result
}
}