R中的最短路径

R中的最短路径,r,shortest-path,median,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 =

我想在随机点之间找到最短的路径。我做了下面的算法,我不确定中间值是否正确,它在点之间画了一条双线。有人能帮我修一下吗

# 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)
        }
    }
}
#我们创建一个具有固定长度和宽度的字段(矩阵)。
#在这里,我们将一些点随机化。
长度=12
breedte=10
安塔彭顿=15
v=0*(1:(长度*宽度))
v[1:aantalpunten]=1
v=样品(v)
punten=矩阵(v、lengte、breedte)
我们在中间的某处建立了一条线,使连接尽可能短。
#这实际上是行和的中位数(毕达哥拉斯)。
rp=行和(punten)
csrp=积温(rp)
m=长度(csrp[csrp 0))
结束=最大值(其中(rp>0))
李宁=c()
#创建中间带
对于(我在begin:(end-1))
{
lijnen=c(lijnen,i,m,i+1,m)
}
#连接其他点
for(我在1:lengte中)
{
对于(j in 1:breedte)
{
if(punten[i,j]>0)
{
lijnen=c(lijnen,i,j,i,m)
}
}
}
lijnen矩阵=矩阵(lijnen,nrow=2,byrow=FALSE)
长度_lijnenmatrix=长度(lijnenmatrix)
图(1,type=“n”,xlab=“”,ylab=“”,xlim=c(0,lengte+2),ylim=c(0,breedte+2))
适用于(i/1:(长度_/4))
{
行(lijnenmatrix[1,c(2*i-1,2*i)],lijnenmatrix[2,c(2*i-1,2*i)])
}
for(我在1:lengte中)
{
对于(j in 1:breedte)
{
if(punten[i,j]>0)
{
第(i,j)点
}
}
}

老实说,我不太了解你想要达到的目标。一条最合适的直线还是什么?我试图在以中间带为约束点的坐标之间找到最短的路线。问题是它绘制了两条直线之间的连接,中间带可能并不总是正确的。@edouard