TIL 41 | Graph
20229 ワード
What is Graph
A graph is an abstract notation used to represent the connection between pairs of objects.
Make a graph
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
}
}
Adding and edgeaddEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1);
}
Removing an edgeremoveEdge(v1, v2) {
this.adjacencyList[v1] = this.adjacencyList[v1].filter((v) => v !== v2);
this.adjacencyList[v2] = this.adjacencyList[v2].filter((v) => v !== v1);
}
Removing a vertexremoveVertex(vertex) {
while (this.adjacencyList[vertex].length) {
const adjacentVertex = this.adjacencyList[vertex].pop();
this.removeEdge(vertex, adjacentVertex);
}
delete this.adjacencyList[vertex];
}
DFS - recursiveDFSRecursive(start) {
const result = [];
const visited = {};
const adjacencyList = this.adjacencyList;
(function dfs(vertex) {
if (!vertex) return null;
visited[vertex] = true;
result.push(vertex);
adjacencyList[vertex].forEach((neighbor) => {
if (!visited[neighbor]) {
return dfs(neighbor);
}
});
})(start);
return result;
}
DFS - iterativeDFSIterative(start) {
const stack = [start];
const result = [];
const visited = {};
let cur;
visited[start] = true;
while (stack.length) {
cur = stack.pop();
result.push(cur);
this.adjacencyList(cur).forEach((neighbor) => {
if (!visited[neighbor]) {
visited[neighbor] = true;
stack.push(neighbor);
}
});
}
return result;
}
BFSBFS(start) {
const queue = [start];
const result = [];
const visited = {};
visited[start] = true;
let cur;
while (queue.length) {
cur = queue.shift();
result.push(cur);
this.adjacencyList[cur].forEach((neighbor) => {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.push(neighbor);
}
});
}
return result;
}
}
Reference
この問題について(TIL 41 | Graph), 我々は、より多くの情報をここで見つけました https://velog.io/@pca0046/TIL-41-Graphテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol