图的最短路径

<script type="text/javascript">

    //图的构建

    function vnode() {

        this.visited = 0;

        this.vertex = 0;

        this.arcs = new Array();

}

function G() {

    this.adjlist = new Array();

}

//0  1  2  3  4  5

var aa = [[0, 7, 8, 0, 0, 9], //0

    [7, 0, 0, 2, 5, 0], //1

    [8, 0, 0, 5, 0, 6], //2

    [0, 2, 5, 0, 9, 0], //3

    [0, 5, 0, 9, 0, 7], //4

    [9, 0, 6, 0, 7, 0]]; //5

function creategraph() {



    var g = new G();

    for (i = 0; i < 6; i++) {

        g.adjlist[i] = new vnode();

        g.adjlist[i].vertex = i;

        g.adjlist[i].arcs = (function () {

            var b=new Array() ;

            for (j = 0; j < 6; j++)

                if (aa[i][j]) b.push(j);

            //alert(b);

            return b;

        })();

    }

    return g;

}

var g=creategraph();

var a=new Array();

var b=new Array();

a.push([0]);

while(a.length)

{

    var l=a.length;

    var temp=g.adjlist[a[0][a[0].length-1]].arcs;

    for(i=0;i<temp.length;i++)

    {





        for(j=0;j<a[0].length;j++)

        {

            if(temp[i]==a[0][j])break;

            if(j==a[0].length-1){a.push(a[0].concat(temp[i]));break;}

        }

    }

    if(l==a.length){b.push(a[0]);}

    a.shift();

}

var s=new Array();

s.push(0);

var  count=1;

while(s.length<6)

{

for(i=0;i<b.length;i++)

{

    if(b[i][count]!=null)

    {

        for(j=0;j<s.length;j++)

        {

            if(s[j]==b[i][count])break;

            if(j==(s.length-1))

            {

                var tmp=(function(){var p=0;for(m=0;m<count;m++)p+=aa[b[i][m]][b[i][m+1]];return p;})();

                

                var v=b[i][count];

                var q=i;

                for(k=i+1;k<b.length;k++)

                {    var t=(function(){var p=0;for(m=0;m<count;m++)p+=aa[b[k][m]][b[k][m+1]];return p;})();

                    

                    if(tmp>t && b[i][count]==b[k][count])

                    {

                        tmp=t;

                        v=b[k][count];

                        q=k;

                    }



                }

                s.push(v);alert(b[q].slice(0,count+1));break;

            }

            

        }



    }





}

count++;

}

</script>

 

你可能感兴趣的:(最短路径)