저는 matrix말고 list방식으로 그래프를 저장하고 경로를 탐색해보았습니다!
class Graph {
constructor() {
this.adjacencyList = [];
}
addvtx(vtx) {
if (this.adjacencyList[vtx] in this.adjacencyList) return;
else {
this.adjacencyList[vtx] = [];
}
return this.adjacencyList;
}
addEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
}
searchingPath(start, destination) {
let tmp = [];
let result = [];
let mark = {};
const dfs = v => {
var node = this.adjacencyList[v];
if (!node) return null;
// 들어오는 족족 tmp에 조합을 넣고
// mark에 새긴다
tmp.push(v);
mark[v] = true;
if (v === destination) {
result.push(tmp.slice());
} else {
for (var nei of node) {
if (mark[nei]) {
continue;
} else {
dfs(nei);
// 끝나면 다시 풀어주고 조합에서 빼버린다.
mark[nei] = false;
tmp.pop();
}
}
}
};
dfs(start);
return result;
}
}
let graph = new Graph();
graph.addvtx(1);
graph.addvtx(2);
graph.addvtx(3);
graph.addvtx(4);
graph.addvtx(5);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 1);
graph.addEdge(2, 3);
graph.addEdge(2, 5);
graph.addEdge(3, 4);
graph.addEdge(4, 2);
graph.addEdge(4, 5);
graph.searchingPath(1,5)