μλ£ κ΅¬μ‘° μ€ Graphμ λν΄μ μμλ΄ λλ€. π
μ΄μ μ₯μΈ Tree ꡬ쑰λ₯Ό 곡λΆνκ³ λ λ€ λ³΄λ©΄ μ’μ΅λλ€! μ©μ΄κ° λΉμ·ν΄μ~
κ·Έλνλ λ Έλμ λ Έλλ₯Ό μ°κ²°νλ κ°μ μ νλλ‘ λͺ¨μλμ μλ£ κ΅¬μ‘°μ λλ€.
μ§νμ² λ Έμ λλ₯Ό μκ°νμλκ² μ’μ΅λλ€ :)
μ©μ΄λ₯Ό λͺκ°μ§ μ 리ν΄λ΄ μλ€.
νΈλ¦¬λ νλμ λΆλͺ¨ λ Έλμμ μλλ‘ λ΄λ €μ€λ κ·ΈλνλΌκ³ ν μ μμ΅λλ€.
κ°λ¨νκ² λμμλ¦¬λ§ μκ°ν΄λ΄ λλ€.
// pseudo Code
κ·Έλν {
store {}, edge {}
method: addNode(κ°) {
storeμ κ°μ { 'κ°': κ° }μΌλ‘ μΆκ°νλ€.
}
method: contains(κ°) {
store['κ°'] μ΄ μλμ§ μ‘°μ¬νλ€.
}
method: removeNode(κ°) {
store['κ°'] μ μ°Ύμ μ κ±°νλ€.
μ κ±°ν λ μ°κ²°λ μ£μ§λ μ κ±°νλ€.
}
method: hasEdge(from, to) {
edge[from] κ° to μΈμ§ μ°Ύλλ€.
}
method: addEdge(from, to) {
edge[from]μ to, edge[to]μ fromμ μΆκ°νλ€.
}
method: removeEdge(from, to) {
delte edge[from], edge[to]
}
method: forEachNode(μ½λ°±) {
storeλ₯Ό λλ©΄μ μ½λ°±(κ°) μ μ€λ€.
}
}
νΉλ³ν 건 μμ΅λλ€.
storeμ edgeκ°μ²΄μ {key: value}ννλ‘ {'κ°':κ°}μ λ£μ΄ ꡬνν©λλ€.
μ€μν μ μ λ Έλλ₯Ό μ§μΈ λ, κ·Έμ μ°κ²°λ μ£μ§λ μ§μμΌ νλ κ²μ λλ€.
κ·Έλ λ€λ©΄ removeNodeμμ μ°κ²°λ μ£μ§λ₯Ό μ°Ύμμ μ κ±°νλ©΄ κ°λ¨ν©λλ€ :)
// Graph
const _ = require('underscore')
const Graph = function() {
this.store = {};
this.edge = {};
};
Graph.prototype.addNode = function(node) {
this.store[node] = node;
};
Graph.prototype.contains = function(node) {
return this.store.hasOwnProperty(node);
};
// 1. 4 --- 5 :
// 2. 4 --- : removeNode(5) -> 5λ λκ° μ°κ²°λμ΄μμ£ ? λ₯Ό λ¬Όμ΄λ΄μ 4λ₯Ό κ°μ Έμ¨λ€λ©΄,
// 3. 4 : removeEdge(κ°μ Έμ¨ 4, 5),
Graph.prototype.removeNode = function(node) {
let tmpNode = this.edge[node]
delete this.store[node]
this.removeEdge(tmpNode, node)
};
Graph.prototype.hasEdge = function(fromNode, toNode) {
return this.edge[fromNode] === toNode;
};
Graph.prototype.addEdge = function(fromNode, toNode) {
this.edge[fromNode] = toNode;
this.edge[toNode] = fromNode;
};
Graph.prototype.removeEdge = function(fromNode, toNode) {
delete this.edge[fromNode];
delete this.edge[toNode];
};
Graph.prototype.forEachNode = function(cb) {
_.each(this.store, node => cb(node))
};