const grid = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
In the grid above, traversing left to right has a cost of 10 and up to down has a cost of 25. I'd like to represent this in a undirected weighted adjacency list like below:
const weightedAdjList = {
0: {1: 10, 3: 25},
1: {2: 10, 4: 25},
2: {5: 25},
3: {4: 10, 5: 25},
4: {5: 10, 7: 25},
5: {8: 25},
6: {7: 10},
7: {8: 10},
8: {}
}
Here is as far as I've gotten with my code:
const matrixToAdjList = (matrix) => {
const graph = {};
let i = 0;
for (let r = 0; r < matrix.length; r++) {
for (let c = 0; c < matrix[0].length; c++) {
if (!(i in graph)) graph[i] = {}
i++
}
}
// populate(graph);
return graph;
};
Can anyone help me out with populating the adjacencies in the graph?
Thank you!