π¨βπ» μ€λ 곡λΆν κ²
μ€λμ μΈμ 리μ€νΈλ₯Ό μΈμ νλ ¬λ‘ λ°κΎΈλ λ‘μ§μ μμ±νλ€.
μΈμ 리μ€νΈλ₯Ό μΈμ νλ ¬λ‘ λ°κΎΈλ κ³Όμ μμ
function addVertex(){
for(let i = 0; i < matrix.length; i++){
matrix.push(0);
}
matrix.push(new Array(matrix.length + 1).fill(0));
}
μ²μμ λ‘μ§μ μ΄λ κ² κ΅¬νν΄μ μλ¬κ° λ¬μλ€.
forλ¬Έμμ matrixλ‘ν΄μ pushλ₯Ό ν κ²½μ° λ€μ matrixκ°
0: 0
1: 0
2: 0
3: [0, 0, 0]
μ΄λ κ² λλ€. κ° property λ§λ€ μ¦ vertex λ§λ€ [0, 0, 0] μ κ°μ΄ μΈμ νλ ¬μ κ°μ ΈμΌνκΈ° λλ¬Έμ [i]λ₯Ό λΆμ¬μ€μΌνλ€.
function μΈμ 리μ€νΈλ₯Ό μΈμ νλ ¬λ‘ λ°κΎΈλ ν¨μ(insertEdges, removeEdges) {
// 1. insertEdegsλλ‘ μ΅λλ²ν
μ€μ μλ₯Ό ꡬνκ³ μ΅λ λ²ν
μ€ μλ§νΌ adjacency Listλ₯Ό ꡬνκ³
// insertEdegseλλ‘ adjacency Listλ₯Ό ꡬμ±νλ€.
// 2. removeEdgesλλ‘ μμ λ§μ°¬κ°μ§λ‘ adjacency Listλ₯Ό ꡬμ±νλ€.
// 3. insertEdegsλ‘ λ§λ adjacency Listμ removeEdgesλ‘ λ§λ adjacency Listλ₯Ό λΉκ΅
// νμ¬ λ§μ½ μ€λ³΅μ΄ μλλ κ²½μ° μλ‘μ΄ adjacency Listμ λ§λ€μ΄ ꡬμ±νλ€.
// 4. μ€λ³΅λλ vertexλ μ μΈν insertAdListλ₯Ό λ§λ λ€.
let maxVertex = insertEdges.reduce((a, c) => {
const bigger = Math.max(...c);
if (bigger > a) return bigger;
return a;
}, 0);
let insertAdList = {};
let removeAdList = {};
for (let i = 0; i <= maxVertex; i++) {
insertAdList[i] = [];
removeAdList[i] = [];
}
for (let i = 0; i < insertEdges.length; i++) {
insertAdList[insertEdges[i][0]].push(insertEdges[i][1]);
insertAdList[insertEdges[i][1]].push(insertEdges[i][0]);
}
for (let i = 0; i < removeEdges.length; i++) {
removeAdList[removeEdges[i][0]].push(removeEdges[i][1]);
removeAdList[removeEdges[i][1]].push(removeEdges[i][0]);
}
for (let i = 0; i < Object.keys(insertAdList).length; i++) {
for (let vertex = 0; vertex < removeAdList[i].length; vertex++) {
if (insertAdList[i].includes(removeAdList[i][vertex])) {
insertAdList[i] = insertAdList[i].filter((el) => el !== removeAdList[i][vertex]);
}
}
}
// 5. adjacency matrixλ₯Ό λ§λ€ κ²μ.
let matrix = [];
function addVertex(){
for(let i = 0; i < matrix.length; i++){
matrix[i].push(0);
}
matrix.push(new Array(matrix.length + 1).fill(0));
}
for(let i = 0; i <= maxVertex; i++){
addVertex();
}
for(let vertex = 0; vertex <= maxVertex; vertex++){
for(let i = 0; i < insertAdList[vertex].length; i++){
matrix[vertex][insertAdList[vertex][i]] = 1;
}
}
return matrix;
}
const insertEdges = [
[0, 2],
[2, 4],
[1, 3],
[2, 1],
];
const removeEdges = [
[0, 3],
[2, 1],
[1, 0],
[4, 2]
];
let output2 = μΈμ 리μ€νΈλ₯Ό μΈμ νλ ¬λ‘ λ°κΎΈλ ν¨μ(insertEdges2, removeEdges2);
console.log(output2);
/**
* [
* [0, 0, 1, 0, 0],
* [0, 0, 0, 1, 0],
* [1, 0, 0, 0, 0],
* [0, 1, 0, 0, 0],
* [0, 0, 0, 0, 0],
* ]
*/