我想在這裏探索一個圖,但我不確定探索函數有什麼問題。遞歸似乎沒有正常工作;當探索節點0的鄰居時,探索0,1,2,然後再回到探索3,4,5;爲什麼?在JavaScript圖形探索算法中的遞歸
explored=[]
//class definition
function graph(){
this.graph=new Array();
this .graph[0] = [1,0,1,1,0,1]
this .graph[1] = [0,1,1,1,0,0]
this .graph[2] = [1,1,1,1,0,0]
this .graph[3] = [1,1,1,1,1,0]
this .graph[4] = [0,0,0,1,1,0]
this .graph[5] = [1,0,0,0,0,0]
this.explore = explore
}
function explore(node,depth){
explored[node]=1
document.write('<br>')
for(x=0;x<depth;x++)
document.write('-')
document.write(node+'<br>')
neighbours=this.graph[node]
document.write('exploring '+node +' neighbours' + neighbours +'explored = '+explored)
for (i=0;i<neighbours.length;i++){
document.write('checking'+i+' node is ='+node)
if(neighbours[i] ==1 && explored[i]!=1)
this.explore(i,++depth)
}
}
g = new graph()
g.explore(0,0)
通過不使用var您已將x和i都設置爲全局變量。 – generalhenry 2011-02-08 08:49:05
@generalhenry你應該讓它成爲答案,所以他可以接受它..如果沒有,我會做.. mohowhah..mwhahahaha! – Frode 2011-02-08 09:15:03