Calculating the shortest route between two points

前端 未结 3 1349
甜味超标
甜味超标 2020-11-28 14:33

I have been working in the past weeks on a multiplayer HTML5 game, using nodejs and websockets.

I\'ve been stuck in this problem for a litt

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 14:57

    While dijkstra algorithm definitely works, in your case the graph is an unweighted graph, so a simple BFS should suffice.

    Pseudo code:

    queue = [startingposition]
    prev = [-1, -1, -1 ...] (array of n elements, all -1)
    while (queue not empty) 
       u <- pop(queue)
       if u = targetposition then DONE! trace the *prev* array for path
       for (v in every unvisited points adjacent to u):
          prev[v] = u
          push v to queue
       end for
    end while
    

    The prev array can also be used to check if a point is visited.

提交回复
热议问题