javascript输出图的简单路径

时间:2020-12-17 19:51:07
<script>
//图的构建
function vnode()
{
this.visited=0;
this.vertex=0;
this.arcs=new Array();
}
function G()
{
this.adjlist=new Array();
}
function creategraph()
{
var a=[[2,3,6],[1,5,4],[4,6,1],[2,3,5],[4,2,6],[3,5,1]];
var g=new G();
for (i=0;i<6;i++)
{
g.adjlist[i]=new vnode();
g.adjlist[i].vertex=i+1;
g.adjlist[i].arcs=a[i];
}
return g;
}
//利用Array的队列性质获取无回路路径
var a=new Array();
a.push([1]);
var g=creategraph();
while(a.length)
{
var temp=g.adjlist[a[0][a[0].length-1]-1].arcs;
for(i=0;i<temp.length;i++)
{
if(temp[i]==6){alert(a[0].concat([6]));continue;}
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]));
}
}
a.shift();
}
</script>