R中的最短路径

时间:2017-07-01 16:58:57

标签: r shortest-path median

我正试图获得随机点之间的最短路径。我做了以下算法,我不确定中位数是否正确,并且它在点之间绘制了一条双线。有人可以帮我解决吗?

# We create a field (matrix) with a fixed length and width.
# there we randomise some points.

lengte = 12
breedte = 10
aantalpunten = 15
v = 0*(1:(lengte*breedte))
v[1:aantalpunten] = 1
v = sample(v) 
punten = matrix(v, lengte, breedte)

# We create a line somewhere in the middle on such way it makes the connections as short as possible.
# This is in fact the median of the rowsums (Pythagoras).

rp = rowSums(punten)
csrp = cumsum(rp)
m = length(csrp[csrp <= ceiling(csrp[length(csrp)]/2)])
punten
m
begin = min(which(rp>0))
end = max(which(rp>0))
lijnen = c()

# create a median

for (i in begin:(end-1))
{
    lijnen = c(lijnen, i, m, i+1, m)
}

# connect other points

for (i in 1:lengte)
{
    for (j in 1:breedte)
    {
        if (punten[i,j] >0)
        {
            lijnen = c(lijnen, i,j,i,m)
        }
    }
}
lijnenmatrix = matrix(lijnen, nrow = 2, byrow = FALSE)
length_lijnenmatrix = length(lijnenmatrix)
plot(1, type="n", xlab="", ylab="",  xlim=c(0, lengte+2), ylim=c(0, breedte+2))
for (i in 1:(length_lijnenmatrix/4))
{
    lines(lijnenmatrix[1, c(2*i-1, 2*i)],lijnenmatrix[2,c(2*i-1, 2*i)])
}
for (i in 1:lengte)
{
    for (j in 1:breedte)
    {
        if (punten[i,j] >0)
        {
            points(i,j)
        }
    }
}

0 个答案:

没有答案