2015-05-04 85 views
1

我想在Python中想出一個貪婪算法,該算法返回給定某個起始頂點的無向圖中的頂點。我知道DFS確定循環是否存在,但我試圖返回形成循環的頂點。我使用鄰接矩陣來表示下面的圖:在無向圖中返回頂點

adjacencyMatrix = [[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]] 

圖示地,這是一個無向圖由一單個週期的。

我目前的思維過程是將我的起始索引設置爲我遇到的第一個1(在此例中爲adjacencyMatrix[0][1])。然後我會查看該行的其餘部分,看看是否有另一個1,因爲這意味着我當前的頂點已連接到該索引。但是,我不完全確定是否(a)這是正確的方法,以及(b)如何「移動」到下一個頂點。例如,我將如何瀏覽嵌套的for循環以從adjacencyMatrix[0][1]頂點移動到頂點?我只需交換行和列索引?

編輯 該解決方案,我想出了,似乎對一些圖形我試了一下工作:

def findCycle(matrix): 
    visited = list() 
    cycleNotFound = True 
    row = 0 
    col = 0 
    startVertex = (0, 0) 

    while cycleNotFound: 

     # Only add a vertex if it has not already been visited 
     if (matrix[row][col] == 1) and ((row, col) not in visited): 
      # Set the startVertex when the first node is found 
      if len(visited) == 0: 
       startVertex = (row, col) 

      # Add the current vertex and its counter part 
      visited.append((row, col)) 
      visited.append((col, row)) 

      # If row and col are equal, infite loop will get created 
      if row != col: 
       row = col 
       col = 0 
      else: 
       row += 1 

     # If back at starting point, break look 
     elif ((row, col) == startVertex) and (len(visited) > 1): 
      cycleNotFound = False 
      visited.append(startVertex) 

     # Else, continue to look for unvisted neighbors 
     else: 
      col += 1 

    return visited 

if __name__ == "__main__": 
    matrix = [[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]] 
    cycle = findCycle(matrix) 
    index = 0 
    # Print the vertices. Only print even vertices to avoid duplicates. 
    while (index < len(cycle)): 
     print cycle[index] 
     index += 2 

它是不是最優雅的解決方案,我敢肯定有一些重大的重構那需要完成。

+0

如果你正在做DFS你去你的鄰居遞歸地之一,從該鄰居你移動到下一個鄰居等 – alfasin

+0

好吧整理後DFS,所以會我只是首先運行DFS來確定是否存在一個循環,然後使用稍微修改的DFS方法返回所有訪問的頂點? – steveclark

+0

首先,鄰接矩陣是對稱的。頂點的數量由矩陣的大小定義。大小爲'n×n'的矩陣意味着有'n'個頂點。要列出連接到某個頂點的頂點,請檢查相應的行爲1,它們的索引「是」您正在查找的頂點。 – PeterE

回答

2

你可以試試這個:

def findCycle(node): 
    cycle = stack() 
    if(DFS(node, cycle)): 
     return cycle 
    return None 

def DFS(node, cycle): 
    cycle.append(node) 
    mark node as visited 
    foreach node.neighbors as neighbor: 
     if neighbor already visited: 
      return true 
     else: 
      if(DFS(neighbor, cycle)) return true 
    cycle.remove(node) 
    return false 
+0

好的,這實際上可能類似於我目前的工作。我假設'neighbors'函數會返回每個'[row] [col] == 1'的列號列表?例如使用提供的鄰接矩陣'1.neighbors'會返回'[2,3]'? – steveclark

+0

是的,你說得對。更新我,如果你發現任何東西。 –

+0

@ steveclark嗨,請選擇我的答案,如果你發現它是正確的。 Thx –