PathFinding.js icon indicating copy to clipboard operation
PathFinding.js copied to clipboard

get the shortest path in a for loop

Open hardyanto opened this issue 8 years ago • 8 comments

I can get the shortest path for the first loop but Why can't I get the shortest path in the subsequent loop? Here are the codes:

var grid = new PF.Grid(numCols, numRows);

var gridBackup = grid.clone();
fnSetObstacles(gridBackup);
var finder = new PF.AStarFinder();

for (var c = 0; c < boothDesignatedCoords.length; c += 2) { var pathToEachDesignatedCoords = finder.findPath(1, 1, boothDesignatedCoords[c], boothDesignatedCoords[c + 1], gridBackup);

}

I can get the shortest path in the subsequent loop if I re-initialise the gridBackup in the for loop. Something like this: for (var c = 0; c < boothDesignatedCoords.length; c += 2) { var gridBackup = grid.clone(); }

But the problem is I have to re assign the obstacles etc. Is there a way for me to get the shortest path in a for loop without re-initializing the gridBackup? Thanks!

hardyanto avatar Feb 07 '17 07:02 hardyanto

Set the obstacles first and then clone the grid.

mfandl avatar Feb 07 '17 07:02 mfandl

But there will be a problem because the shortest path finding in the for loop cannot use the obstacles.

hardyanto avatar Feb 07 '17 07:02 hardyanto

then i dont understand. i thought that by setting obstacles you mean adding additional non-walkable cells to the grid

mfandl avatar Feb 07 '17 07:02 mfandl

sorry for the confusion. I mean yes you are right. I mean I want it to use the obstacles as additional non-walkable cells

hardyanto avatar Feb 07 '17 08:02 hardyanto

But how? LOL

hardyanto avatar Feb 07 '17 08:02 hardyanto

Wait, I think I get it now.

Would something like this work if you use the workingGrid in the for loop?

var gridWithObstacles = grid.clone();
var workingGrid;
fnSetObstacles(gridWithObstacles);

for(;;) {
  workingGrid = gridWithObstacles.clone();
  ...
}

Also, if grid is really just an empty grid and you do not need to reuse it, you do not need to clone it. The important thing is that you can not use the grid you clone from and clone the grid that already has set everything you need.

mfandl avatar Feb 07 '17 08:02 mfandl

Thank you so much for helping me :)

hardyanto avatar Feb 07 '17 08:02 hardyanto

it works

hardyanto avatar Feb 07 '17 08:02 hardyanto