Skip to content

Commit e86a6e4

Browse files
committed
Add data structure tree and graph
1 parent 7948d11 commit e86a6e4

File tree

16 files changed

+1587
-0
lines changed

16 files changed

+1587
-0
lines changed

src/data-structures/graph/Graph.js

Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
export default class Graph {
2+
/**
3+
* @param {boolean} isDirected
4+
*/
5+
constructor(isDirected = false) {
6+
this.vertices = {};
7+
this.edges = {};
8+
this.isDirected = isDirected;
9+
}
10+
11+
/**
12+
* @param {GraphVertex} newVertex
13+
* @returns {Graph}
14+
*/
15+
addVertex(newVertex) {
16+
this.vertices[newVertex.getKey()] = newVertex;
17+
18+
return this;
19+
}
20+
21+
/**
22+
* @param {string} vertexKey
23+
* @returns Đỉnh đồ thị.
24+
*/
25+
getVertexByKey(vertexKey) {
26+
return this.vertices[vertexKey];
27+
}
28+
29+
/**
30+
* @param {GraphVertex} vertex
31+
* @returns {GraphVertex[]}
32+
*/
33+
getNeighbors(vertex) {
34+
return vertex.getNeighbors();
35+
}
36+
37+
/**
38+
* @return {GraphVertex[]}
39+
*/
40+
getAllVertices() {
41+
return Object.values(this.vertices);
42+
}
43+
44+
/**
45+
* @return {GraphEdge[]}
46+
*/
47+
getAllEdges() {
48+
return Object.values(this.edges);
49+
}
50+
51+
/**
52+
* @param {GraphEdge} edge
53+
* @returns {Graph}
54+
*/
55+
addEdge(edge) {
56+
// Tìm đỉnh bắt đầu và kết thúc.
57+
let startVertex = this.getVertexByKey(edge.startVertex.getKey());
58+
let endVertex = this.getVertexByKey(edge.endVertex.getKey());
59+
60+
// Chèn đỉnh bắt đầu vào nếu nó chưa được chèn.
61+
if (!startVertex) {
62+
this.addVertex(edge.startVertex);
63+
startVertex = this.getVertexByKey(edge.startVertex.getKey());
64+
}
65+
66+
// Chèn đỉnh kết thúc vào nếu nó chưa được chèn.
67+
if (!endVertex) {
68+
this.addVertex(edge.endVertex);
69+
endVertex = this.getVertexByKey(edge.endVertex.getKey());
70+
}
71+
72+
// Kiểm tra nếu cạnh đã tồn tại.
73+
if (this.edges[edge.getKey()]) {
74+
throw new Error('Edge has already been added before');
75+
} else {
76+
this.edges[edge.getKey()] = edge;
77+
}
78+
79+
// Thêm cạnh cho đỉnh.
80+
if (this.isDirected) {
81+
// Nếu đồ thị là có hướng chỉ thêm cạnh vào đỉnh bắt đầu.
82+
startVertex.addEdge(edge);
83+
} else {
84+
// Nếu đồ thị là vô hướng thêm cạnh cho cả hai đỉnh.
85+
startVertex.addEdge(edge);
86+
endVertex.addEdge(edge);
87+
}
88+
89+
return this;
90+
}
91+
92+
/**
93+
* @param {GraphEdge} edge
94+
*/
95+
deleteEdge(edge) {
96+
// Xoá cạnh khỏi tập hợp cạnh.
97+
if (this.edges[edge.getKey()]) {
98+
delete this.edges[edge.getKey()];
99+
} else {
100+
throw new Error('Edge not found in graph');
101+
}
102+
103+
// Tìm đỉnh bắt đầu và kết thúc và xoá cạnh khỏi chúng
104+
const startVertex = this.getVertexByKey(edge.startVertex.getKey());
105+
const endVertex = this.getVertexByKey(edge.endVertex.getKey());
106+
107+
startVertex.deleteEdge(edge);
108+
endVertex.deleteEdge(edge);
109+
}
110+
111+
/**
112+
* @param {GraphVertex} startVertex
113+
* @param {GraphVertex} endVertex
114+
* @return {(GraphEdge|null)}
115+
*/
116+
findEdge(startVertex, endVertex) {
117+
const vertex = this.getVertexByKey(startVertex.getKey());
118+
119+
if (!vertex) {
120+
return null;
121+
}
122+
123+
return vertex.findEdge(endVertex);
124+
}
125+
126+
/**
127+
* @return {number}
128+
*/
129+
getWeight() {
130+
return this.getAllEdges().reduce((weight, graphEdge) => {
131+
return weight + graphEdge.weight;
132+
}, 0);
133+
}
134+
135+
/**
136+
* Đảo tất cả cạnh của đồ thị có hướng.
137+
* @return {Graph}
138+
*/
139+
reverse() {
140+
/** @param {GraphEdge} edge */
141+
this.getAllEdges().forEach((edge) => {
142+
// Xóa cạnh thẳng khỏi đồ thị và khỏi các đỉnh.
143+
this.deleteEdge(edge);
144+
145+
// Đảo cạnh.
146+
edge.reverse();
147+
148+
// Thêm cạnh đảo ngược trở lại đồ thị và các đỉnh của nó.
149+
this.addEdge(edge);
150+
});
151+
152+
return this;
153+
}
154+
155+
/**
156+
* @return {object}
157+
*/
158+
getVerticesIndices() {
159+
const verticesIndices = {};
160+
this.getAllVertices().forEach((vertex, index) => {
161+
verticesIndices[vertex.getKey()] = index;
162+
});
163+
164+
return verticesIndices;
165+
}
166+
167+
/**
168+
* @return {*[][]}
169+
*/
170+
getAdjacencyMatrix() {
171+
const vertices = this.getAllVertices();
172+
const verticesIndices = this.getVerticesIndices();
173+
174+
// Tạo ma trận với vô hạn số nghĩa là không có cách nào
175+
// để đi từ đỉnh này sang đỉnh khác.
176+
const adjacencyMatrix = Array(vertices.length).fill(null).map(() => {
177+
return Array(vertices.length).fill(Infinity);
178+
});
179+
180+
// Điền đấy các cột.
181+
vertices.forEach((vertex, vertexIndex) => {
182+
vertex.getNeighbors().forEach((neighbor) => {
183+
const neighborIndex = verticesIndices[neighbor.getKey()];
184+
adjacencyMatrix[vertexIndex][neighborIndex] = this.findEdge(vertex, neighbor).weight;
185+
});
186+
});
187+
188+
return adjacencyMatrix;
189+
}
190+
191+
/**
192+
* @return {string}
193+
*/
194+
toString() {
195+
return Object.keys(this.vertices).toString();
196+
}
197+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
export default class GraphEdge {
2+
/**
3+
* @param {GraphVertex} startVertex
4+
* @param {GraphVertex} endVertex
5+
* @param {number} [weight=1]
6+
*/
7+
constructor(startVertex, endVertex, weight = 0) {
8+
this.startVertex = startVertex;
9+
this.endVertex = endVertex;
10+
this.weight = weight;
11+
}
12+
13+
/**
14+
* @return {string}
15+
*/
16+
getKey() {
17+
const startVertexKey = this.startVertex.getKey();
18+
const endVertexKey = this.endVertex.getKey();
19+
20+
return `${startVertexKey}_${endVertexKey}`;
21+
}
22+
23+
/**
24+
* @return {GraphEdge}
25+
*/
26+
reverse() {
27+
const tmp = this.startVertex;
28+
this.startVertex = this.endVertex;
29+
this.endVertex = tmp;
30+
31+
return this;
32+
}
33+
34+
/**
35+
* @return {string}
36+
*/
37+
toString() {
38+
return this.getKey();
39+
}
40+
}
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
import LinkedList from '../linked-list/LinkedList';
2+
3+
export default class GraphVertex {
4+
/**
5+
* @param {*} value
6+
*/
7+
constructor(value) {
8+
if (value === undefined) {
9+
throw new Error('Graph vertex must have a value');
10+
}
11+
12+
/**
13+
* @param {GraphEdge} edgeA
14+
* @param {GraphEdge} edgeB
15+
*/
16+
const edgeComparator = (edgeA, edgeB) => {
17+
if (edgeA.getKey() === edgeB.getKey()) {
18+
return 0;
19+
}
20+
21+
return edgeA.getKey() < edgeB.getKey() ? -1 : 1;
22+
};
23+
24+
// Thông thường ta sẽ lưu chuỗi value như tên đỉnh
25+
// Nhưng nó cũng có thể là bất kỳ đối tượng nào.
26+
this.value = value;
27+
this.edges = new LinkedList(edgeComparator);
28+
}
29+
30+
/**
31+
* @param {GraphEdge} edge
32+
* @returns {GraphVertex}
33+
*/
34+
addEdge(edge) {
35+
this.edges.append(edge);
36+
37+
return this;
38+
}
39+
40+
/**
41+
* @param {GraphEdge} edge
42+
*/
43+
deleteEdge(edge) {
44+
this.edges.delete(edge);
45+
}
46+
47+
/**
48+
* @returns {GraphVertex[]}
49+
*/
50+
getNeighbors() {
51+
const edges = this.edges.toArray();
52+
53+
/** @param {LinkedListNode} node */
54+
const neighborsConverter = (node) => {
55+
return node.value.startVertex === this ? node.value.endVertex : node.value.startVertex;
56+
};
57+
58+
// Trả về đỉnh bắt đầu hoặc kết thúc.
59+
// Đối với đồ thị vô hướng, có thể đỉnh hiện tại sẽ là đỉnh cuối.
60+
return edges.map(neighborsConverter);
61+
}
62+
63+
/**
64+
* @return {GraphEdge[]}
65+
*/
66+
getEdges() {
67+
return this.edges.toArray().map((linkedListNode) => linkedListNode.value);
68+
}
69+
70+
/**
71+
* @return {number}
72+
*/
73+
getDegree() {
74+
return this.edges.toArray().length;
75+
}
76+
77+
/**
78+
* @param {GraphEdge} requiredEdge
79+
* @returns {boolean}
80+
*/
81+
hasEdge(requiredEdge) {
82+
const edgeNode = this.edges.find({
83+
callback: (edge) => edge === requiredEdge,
84+
});
85+
86+
return !!edgeNode;
87+
}
88+
89+
/**
90+
* @param {GraphVertex} vertex
91+
* @returns {boolean}
92+
*/
93+
hasNeighbor(vertex) {
94+
const vertexNode = this.edges.find({
95+
callback: (edge) => edge.startVertex === vertex || edge.endVertex === vertex,
96+
});
97+
98+
return !!vertexNode;
99+
}
100+
101+
/**
102+
* @param {GraphVertex} vertex
103+
* @returns {(GraphEdge|null)}
104+
*/
105+
findEdge(vertex) {
106+
const edgeFinder = (edge) => {
107+
return edge.startVertex === vertex || edge.endVertex === vertex;
108+
};
109+
110+
const edge = this.edges.find({ callback: edgeFinder });
111+
112+
return edge ? edge.value : null;
113+
}
114+
115+
/**
116+
* @returns {string}
117+
*/
118+
getKey() {
119+
return this.value;
120+
}
121+
122+
/**
123+
* @return {GraphVertex}
124+
*/
125+
deleteAllEdges() {
126+
this.getEdges().forEach((edge) => this.deleteEdge(edge));
127+
128+
return this;
129+
}
130+
131+
/**
132+
* @param {function} [callback]
133+
* @returns {string}
134+
*/
135+
toString(callback) {
136+
return callback ? callback(this.value) : `${this.value}`;
137+
}
138+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Đồ thị
2+
3+
Trong khoa học máy tính, **đồ thị** là một kiểu dữ liệu trừu tượng để triển khai đồ thị vô hướng và có hướng trong toán học, đặc biệt trong mảng lý thuyết đồ thị.
4+
5+
Cấu trúc dữ liệu đồ thị bao gồm một hữu hạn (có thể thay đổi) tập hợp đỉnh hoặc nút hoặc điểm, cùng với một tập hợp không tuần tự cặp đỉnh cho đồ thị vô hướng và tập hợp tuần tự cặp đỉnh cho đồ thị có hướng. Cặp đỉnh còn được biết đến là cạnh, vòng hoặc đoạn trong đồ thị vô hướng và là mũi tên, cạnh có hướng hoặc đoạn có hướng trong đồ thị có hướng. Các đỉnh có thể là một phần của cấu trúc đồ thị hoặc có thể là các thực thể bên ngoài được biểu diễn bằng các chỉ số nguyên hoặc tham chiếu.
6+
7+
![Graph](https://www.tutorialspoint.com/data_structures_algorithms/images/graph.jpg)
8+
9+
## Liên kết
10+
11+
- [Wikipedia](https://en.wikipedia.org/wiki/Graph_(abstract_data_type))
12+
- [Introduction to Graphs on YouTube](https://www.youtube.com/watch?v=gXgEDyodOJU&index=9&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
13+
- [Graphs representation on YouTube](https://www.youtube.com/watch?v=k1wraWzqtvQ&index=10&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)

0 commit comments

Comments
 (0)