得到两个点之间的最短路径 [英] Get the shortest way between two point

查看:220
本文介绍了得到两个点之间的最短路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的数组:

steps=[
    {from:1, to:8},
    {from:1, to:2},
    {from:2, to:7},
    {from:7, to:9},
    {from:8, to:9}
];

这阵是描述在哪里呢,它有两个点之间的连接。例如,从1至7,有一种方法1-> 2-> 7

this array is describe where does it has connection between two point. For example from 1 to 7 there is a way 1->2->7.

在JavaScript的我怎么能生成例如最短的方式,从1到9?

In JavaScript how can I generate the for example the shortest way from 1 to 9?

更新

function calc_route(start, end, data)
    {           
        console.log(start+", "+end);
        console.log(data);              
        for(var i=0; i<data.length; i++)
        {

            if(data[i].topoint == end && data[i].frompoint == start)
            {
                console.log("Return");                  
                console.log(data[i]);
                return data[i];
            }
            else
            {
                if(data[i].frompoint == start)
                {                       
                    calcfor =   data.splice(i, 1);                                      
                    calc_route(calcfor[0].topoint, end, data);
                }
            }
        }
    }

这是我做的到现在为止,我的问题是我怎么能保存路径?

This is what I done until now, my question is how can I save the path?

推荐答案

下面是解决方案:

function calc_route(start, end, data, mypath, solution)
        {               
            mypath.push(parseInt(start));
            for(var i=0; i<data.length; i++)
            {

                if(data[i].topoint == end && data[i].frompoint == start)
                {
                    mypath.push(end);
                    solution.push(mypath);
                    return end;
                }
                else
                {

                    if(data[i].frompoint == start)
                    {                                   
                        calcfor =   data.slice(0);  
                        calcfor.splice(i,1);                                    
                        calc_route(data[i].topoint, end, calcfor, mypath.slice(0), solution);
                    }
                }
            }
        }

这篇关于得到两个点之间的最短路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆