I am working on the undirected graph. I don’t understand why does it overwrites the data in Array when I’m using .push() . I can get these normal while console.log the variable besides pushing the data of it to an Array. Below is the code. At printAllPathsUtils function.
let v;
let nearList;
let result = [];
function Graph(vertics) {
v = vertics;
initAdjList();
}
function initAdjList() {
adjList = new Array(v);
for (var i = 0; i < v; i++) {
adjList[i] = [];
}
}
function addNode(s, d) {
adjList[s].push(d);
}
function printPaths(s, d) {
let isVisited = new Array(v);
for (var i = 0; i < v; i++) {
isVisited[i] = false;
}
let pathList = [];
pathList.push(s);
printPathsUtil(s, d, isVisited, pathList);
}
function printPathsUtil(u, d, isVisited, pathListLocal) {
if (u == d) {
result.push(pathListLocal);
console.log(result)
return;
}
isVisited[u] = true;
for (var i = 0; i < adjList[u].length; i++) {
if (!isVisited[adjList[u][i]]) {
pathListLocal.push(adjList[u][i]);
printPathsUtil(adjList[u][i], d, isVisited, pathListLocal);
pathListLocal.splice(pathListLocal.indexOf(adjList[u][i]), 1);
}
}
isVisited[u] = false;
}
Graph(6);
addNode(0, 3);
addNode(0, 5);
addNode(1, 4);
addNode(1, 5);
addNode(2, 3);
addNode(2, 4);
addNode(3, 2);
addNode(3, 0);
addNode(3, 4);
addNode(3, 5);
addNode(4, 1);
addNode(4, 2);
addNode(4, 3);
addNode(4, 5);
addNode(5, 0);
addNode(5, 1);
addNode(5, 3);
addNode(5, 4);
var s = 0;
var d = 5;
printPaths(s, d)
In if(u == d)
, there is where the problem occur. While using console log, I can get what I expect, but using result.push(pathListLocal)
, it’s giving me back a weird result. You can see the screenshot from the terminal below. That’s what I have got while using result.push(pathListLocal)
and console.log(result)
at the same time.
When using console.log(pathListLocal)
alone, this is what I got:
What I want to do is put the result from pathListLocal
into the Array result
. Anyone have clue on how is this happening?
Edit: In more straight way, I would like to have [[ 0, 3, 2, 4, 1, 5 ],[ 0, 3, 2, 4, 5 ], [ 0, 3, 4, 1, 5 ], [ 0, 3, 4, 5 ], [ 0, 3, 5 ], [ 0, 5 ]]
from the variable result