在無向圖中,邊是雙向的,因此構建鄰接表時需要考慮兩個方向。下面是一個簡單的 JavaScript 代碼示例,用于構建無向圖的鄰接表:
// 示例數據
const links = [{ source: 1, target: 0 },{ source: 2, target: 0 },// ... 其他鏈接
];// 構建無向圖的鄰接表
function buildUndirectedGraph(links) {const graph = {};for (const link of links) {// 對于每條邊,將兩個方向都添加到鄰接表中if (!graph[link.source]) {graph[link.source] = [];}graph[link.source].push(link.target);if (!graph[link.target]) {graph[link.target] = [];}graph[link.target].push(link.source);}return graph;
}// 使用示例
const undirectedGraph = buildUndirectedGraph(links);// 打印鄰接表
for (const node in undirectedGraph) {const neighbors = undirectedGraph[node];console.log(`Node ${node}: Neighbors ${neighbors.join(', ')}`);
}
這個代碼會遍歷所有的邊,對于每條邊,分別將兩個方向的節點添加到對方的鄰接表中。這樣就構建了一個無向圖的鄰接表。在打印鄰接表時,你可以看到每個節點的鄰居節點。這個鄰接表是一個表示無向圖的數據結構,可用于各種圖算法。