Algorithm to find two points furthest away from each other

前端 未结 9 1319
闹比i
闹比i 2020-12-13 06:23

Im looking for an algorithm to be used in a racing game Im making. The map/level/track is randomly generated so I need to find two locations, start and goal, that makes use

9条回答
  •  囚心锁ツ
    2020-12-13 07:10

    Raimund Seidel gives a simple method using matrix multiplication to compute the all-pairs distance matrix on an unweighted, undirected graph (which is exactly what you want) in the first section of his paper On the All-Pairs-Shortest-Path Problem in Unweighted Undirected Graphs [pdf].

    The input is the adjacency matrix and the output is the all-pairs shortest-path distance matrix. The run-time is O(M(n)*log(n)) for n points where M(n) is the run-time of your matrix multiplication algorithm.

    The paper also gives the method for computing the actual paths (in the same run-time) if you need this too.

    Seidel's algorithm is cool because the run-time is independent of the number of edges, but we actually don't care here because our graph is sparse. However, this may still be a good choice (despite the slightly-worse-than n^2 run-time) if you want the all pairs distance matrix, and this might also be easier to implement and debug than floodfill on a maze.

    Here is the pseudocode:

    Let A be the nxn (0-1) adjacency matrix of an unweighted, undirected graph, G
    
    All-Pairs-Distances(A)
        Z = A * A
        Let B be the nxn matrix s.t. b_ij = 1 iff i != j and (a_ij = 1 or z_ij > 0)
        if b_ij = 1 for all i != j return 2B - A //base case
        T = All-Pairs-Distances(B)
        X = T * A
        Let D be the nxn matrix s.t. d_ij = 2t_ij if x_ij >= t_ij * degree(j), otherwise d_ij = 2t_ij - 1
        return D
    

    To get the pair of points with the greatest distance we just return argmax_ij(d_ij)

提交回复
热议问题