forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph3.js
More file actions
Latest commit
108 lines (89 loc) · 2.24 KB
/
Copy pathGraph3.js
File metadata and controls
108 lines (89 loc) · 2.24 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
classGraph{
constructor(){
this.adjacencyObject={}
}
addVertex(vertex){
if(!this.adjacencyObject[vertex])this.adjacencyObject[vertex]=[]
}
addEdge(vertex1,vertex2){
this.adjacencyObject[vertex1].push(vertex2)
this.adjacencyObject[vertex2].push(vertex1)
}
removeEdge(vertex1,vertex2){
this.adjacencyObject[vertex1]=this.adjacencyObject[vertex1].filter(
(v)=>v!==vertex2
)
this.adjacencyObject[vertex2]=this.adjacencyObject[vertex2].filter(
(v)=>v!==vertex1
)
}
removeVertex(vertex){
while(this.adjacencyObject[vertex].length){
constadjacentVertex=this.adjacencyObject[vertex].pop()
this.removeEdge(vertex,adjacentVertex)
}
}
/**
* Return DFS (Depth First Search) List Using Recursive Method
*/
DFS(start){
if(!start)returnnull
constresult=[]
constvisited={}
constadjacencyObject=this.adjacencyObject
functiondfs(vertex){
if(!vertex)returnnull
visited[vertex]=true
result.push(vertex)
adjacencyObject[vertex].forEach((neighbor)=>{
if(!visited[neighbor]){
dfs(neighbor)
}
})
}
dfs(start)
returnresult
}
/**
* Return DFS(Depth First Search) List Using Iteration
*/
DFSIterative(start){
if(!start)returnnull
conststack=[start]
constvisited={}
visited[start]=true
constresult=[]
letcurrentVertex
while(stack.length){
currentVertex=stack.pop()
result.push(currentVertex)
this.adjacencyObject[currentVertex].forEach((neighbor)=>{
if(!visited[neighbor]){
visited[neighbor]=true
stack.push(neighbor)
}
})
}
returnresult
}
BFS(start){
if(!start)returnnull
constqueue=[start]
constvisited={}
visited[start]=true
letcurrentVertex
constresult=[]
while(queue.length){
currentVertex=queue.shift()
result.push(currentVertex)
this.adjacencyObject[currentVertex].forEach((neighbor)=>{
if(!visited[neighbor]){
visited[neighbor]=true
queue.push(neighbor)
}
})
}
returnresult
}
}
export{Graph}