2013-10-12 82 views
0

我已經實現了廣度優先搜索。鄰接矩陣(adj [] [])表示不同節點之間的關係,節點存儲在節點[]中。BFS的實現

但是,我沒有得到所需的遍歷。請幫助我。以下是我的代碼。沒有語法錯誤。這可能是一個邏輯錯誤,我無法通過調試發現。

insert(nodes[0]); 
nos = nos + 1; 
visited[nos] = nodes[0]; 
while(front != -1) 
{ 
char ch = remove(); 
for(int i=0;i<n;i++) 
{ 
    if(ch == nodes[i]) 
    { 
       pos = i; 
    } 
} 
for(int j=0;j<n;j++) 
{ 
     if(adj[j][pos] == 1) 
     { 
      for(int k=0;k<=nos;k++) 
      { 
        if(visited[k] == nodes[j]) 
        { 
         goto end; 
        } 
      } 
      nos = nos + 1; 
      visited[nos] = nodes[j]; 
      insert(nodes[j]); 
      end:continue; 
     } 
} 
} 
+0

爲什麼插入'節點[someindex]'然後還要再看看它,而不是僅僅將'someindex'?另外 - 爲什麼你只能從索引1插入到visited []中? – Leeor

+0

最初nos = -1 –

+0

好吧,節點[]'的內容是什麼?它是獨特的嗎?因爲所有'visited []'比較只會在那時起作用。爲什麼不把索引放在'visited []'中? – Leeor

回答

0

試試這個..這似乎是爲我工作

def bfs(graph, start, goal): 
    if start == goal: 
     return None 

    frontier = [start] 
    explored = [] 
    num_explored = 0 
    while len(frontier) > 0: 
    node = frontier.pop(0) 

    explored.append(node) 
    for edge in networkx.edges(graph, node): 
     child = State(graph, node) 

     if (child not in explored) and (child not in frontier): 
      if child == goal: 
       print "Path found in BFS" 
       return child 
      else: 
       frontier.append(child) 
      num_explored = num_explored + 1 
    print "BFS path failed" 

    return None