Search code examples
algorithmdictionarypoints

Determining Points User Can Reach on a Map


If I have a PHP Map defined as such

$map = array(
    '0' => array('1','2','3','4'),
    '1' => array('0','5'),
    '2' => array('0','6'),
    '3' => array('0','7'),
    '4' => array('0','8'),
    '5' => array('1','9','10'),
    '6' => array('2','10','11'),
    '7' => array('3','11','12'),
    '8' => array('4','12','9'),
    '9' => array('8','5'),
    '10' => array('5','6'),
    '11' => array('6','7'),
    '12' => array('7','8'),
);

which looks like this:

9-------5-------10
|       |       |
|       1       |
|       |       |
8---4---0---2---6
|       |       |
|       3       |
|       |       |
12------8-------11

Now from this, lets say I am at position 1, and I can move 4 (and exactly 4) places, how can I work which positions the user can move to?


Solution

  • I would do the following (in pseudocode):

    reachable={1}
    for i=0 to 4 (exclusive)
      newreachable={}
      for elem in reachable
        add map[elem] to newreachable
      reachable=newreachable
    

    For each iteration, reachable contains the positions in which it is possible to be, and newreachable gets each of the positions to which you can move.