1. 배열 사용
function createAdjacencyList(edges, nodeCount) {
const adjacencyList = Array.from({ length: nodeCount + 1 }, () => []);
for (const [u, v] of edges) {
adjacencyList[u].push(v);
adjacencyList[v].push(u);
}
return adjacencyList;
}
// 입력값
const nodeCount = 6;
const edgeList = [
[1, 2],
[2, 5],
[5, 1],
[3, 4],
[4, 6]
];
// 인접 리스트 생성
const adjacencyList = createAdjacencyList(edgeList, nodeCount);
// 출력
adjacencyList.forEach((nodes, index) => {
if (index !== 0) console.log(index, ":", nodes);
});
2. Map 객체 사용
function createAdjacencyList(edges, nodeCount) {
const adjacencyList = new Map();
// 노드 개수만큼 빈 배열을 미리 초기화
for (let i = 1; i <= nodeCount; i++) {
adjacencyList.set(i, []);
}
// 양방향 그래프이므로 양쪽에 추가
for (const [u, v] of edges) {
adjacencyList.get(u).push(v);
adjacencyList.get(v).push(u);
}
return adjacencyList;
}
// 입력값
const nodeCount = 6;
const edgeList = [
[1, 2],
[2, 5],
[5, 1],
[3, 4],
[4, 6]
];
// 인접 리스트 생성
const adjacencyList = createAdjacencyList(edgeList, nodeCount);
// 출력
for (let [key, value] of adjacencyList) {
console.log(key, ":", value);
}
📌 출력 결과
1 : [ 2, 5 ]
2 : [ 1, 5 ]
3 : [ 4 ]
4 : [ 3, 6 ]
5 : [ 2, 1 ]
6 : [ 4 ]
배열을 사용하면 메모리 효율이 좋고, Map을 사용하면 키 값을 유연하게 설정할 수 있다.
'알고리즘 > 자료구조' 카테고리의 다른 글
[백준] 2346번: 풍선 터뜨리기 (실버 3) - Javascript 풀이 (시간초과) (0) | 2025.02.27 |
---|---|
[백준] 1158번 : 요세푸스 문제 (실버 4) - Javascript 풀이 (1) | 2025.02.11 |
[백준] 2164번: 카드2 (실버4) - Javascript 풀이 (0) | 2025.02.09 |
[프로그래머스] Lv 2. 올바른 괄호 - Javascript 풀이 (0) | 2025.02.07 |
[프로그래머스] Lv 2. 기능 개발 - Javascript 풀이 (1) | 2025.02.05 |