How can I find the shortest path between 100 moving targets? (Live demo included.)

后端 未结 4 544
情话喂你
情话喂你 2021-01-29 21:42

Background

This picture illustrates the problem: \"square_grid_with_arrows_giving_directions\"

I can cont

4条回答
  •  执笔经年
    2021-01-29 22:05

    Greedy method

    One approach suggested in the comments is to go to the closest target first.

    I've put up a version of the demo which includes the cost calculated via this greedy method here.

    The code is:

    function greedyMethod(start_x,start_y) {
      var still_to_visit = (1<

    For 10 targets it is around twice the optimal distance, but sometimes much more (e.g. *4) and occasionally even hits the optimum.

    This approach is very efficient so I can afford some cycles to improve the answer.

    Next I'm considering using ant colony methods to see if they can explore the solution space effectively.

    Ant colony method

    An Ant colony method seems to work remarkable well for this problem. The link in this answer now compares the results when using both greedy and ant colony method.

    The idea is that ants choose their route probabilistically based on the current level of pheromone. After every 10 trials, we deposit additional pheromone along the shortest trail they found.

    function antMethod(start_x,start_y) {
      // First establish a baseline based on greedy
      var L = greedyMethod(start_x,start_y);
      var n = pts.length;
      var m = 10; // number of ants
      var numrepeats = 100;
      var alpha = 0.1;
      var q = 0.9;
      var t0 = 1/(n*L);
    
      pheromone=new Array(n+1); // entry n used for starting position
      for(i=0;i<=n;i++) {
        pheromone[i] = new Array(n);
        for(j=0;jbestc) {
                  besti = i;
                  bestc = c;
                }
              }
            }
            if (Math.random()>0.9) {
              thresh = totalh*Math.random();
              for(i=0;i

    Results

    This ant colony method using 100 repeats of 10 ants is still very fast (37ms for 16 targets compared to 3700ms for the exhaustive search) and seems very accurate.

    The table below shows the results for 10 trials using 16 targets:

       Greedy   Ant     Optimal
       46       29      29
       91       38      37
      103       30      30
       86       29      29
       75       26      22
      182       38      36
      120       31      28
      106       38      30
       93       30      30
      129       39      38
    

    The ant method seems significantly better than greedy and often very close to optimal.

提交回复
热议问题