네이게이션 길찾기
게임 내 캐릭터 이동
지식 그래프 ⇒ 연관검색어
쾨니히스베르크의 다리 문제
화살표로 방향을 표현하며, 방향성이 있는 그래프
방향이 있는 그래프는 순서대로만 노드를 이동 가능
무방향 그래프는 반대 방향으로도 이동 가능
엣지에 가중치가 주어진 그래프
양수 및 음수 가중치 가능
class WeightedGraph {
constructor(size) {
this.size = size;
this.matrix = [];
this.init();
}
init() {
for (let i = 0; i < this.size; i++) {
this.matrix[i] = new Array(this.size).fill(Infinity);
}
for (let i = 0; i < this.size; i++) {
this.matrix[i][i] = 0;
}
}
addEdge(from, to, weight = 1) {
if (from >= this.size || from < 0 || to >= this.size || to < 0) return null;
this.matrix[from][to] = weight;
}
printWeightedGraph() {
for (let i = 0; i < this.size; i++) {
console.log(
this.matrix[i]
.map((weight) => (weight === Infinity ? '♾️' : weight))
.join(' '),
);
}
}
}
class ListGraph {
constructor() {
this.adjList = new Map();
}
addVertex(vertex) {
if (!this.adjList.has(vertex)) this.adjList.set(vertex, []);
}
addEdge(from, to, weight = 1) {
if (!this.adjList.has(from)) this.addVertex(from);
if (!this.adjList.has(to)) this.addVertex(to);
this.adjList.get(from).push({ node: to, weight: weight });
}
printListGraph() {
for (let [vertex, edges] of this.adjList) {
let edgeList = edges
.map((edge) => `${edge.node}(${edge.weight})`)
.join(', ');
console.log(`${vertex} -> ${edgeList}`);
}
}
}