2013-04-24 147 views
-3

如何檢測如果一個圖具有周期或不從該部分的代碼,其示出了檢測週期深度優先搜索的曲線圖是在鄰接矩陣從格拉夫

// ------------------------------------------------------------ 
    public void dfs() // depth-first search 
    { // begin at vertex 0 
     int k = 0; 
     vertexList[0].wasVisited = true; // mark it 
     displayVertex(0); // display it 
     theStack.push(0); // push it 
     while (!theStack.isEmpty()) // until stack empty, 
     { 
      // get an unvisited vertex adjacent to stack top 
      int v = getAdjUnvisitedVertex(theStack.peek()); 
      int x = nAdjVisitedVertex(v); 

      if (v == -1) // if no such vertex, 
       theStack.pop(); 
      else // if it exists, 
      { 
       vertexList[v].wasVisited = true; // mark it 
       displayVertex(v); // display it 
       if (x == 2) 
        k++; 

       theStack.push(v); // push it 

      } 
     } // end while 
      // stack is empty, so we’re done 
     for (int j = 0; j < nVerts; j++) 
      // reset flags 
      vertexList[j].wasVisited = false; 

     if(k != 0) 
      System.out.println("not a cycle"); 
     else 
      System.out.println("cycle"); 

    } // end dfs 
+0

你似乎在努力提出好問題。我們是一個非常有幫助的社區,但是如果您提出一個深思熟慮的問題,表明您已經付出了一些努力,那麼您會發現我們更有幫助。請閱讀該網站的FAQS。 – coder 2013-04-24 17:08:00

+0

這是一個有向還是無向的圖? – 2013-04-24 17:08:11

+0

@workInAFishBowl對不起,我在網上搜索,但我今天需要這個!我只需要一個想法來實現它自己而不是整個代碼。 – mpluse 2013-04-24 17:11:14

回答

1

實現在遍歷該圖,你需要繼續尋找已經訪問過的節點。如果您遇到已經訪問過的節點,則會發現一個循環。如果遍歷完成而沒有獲取任何訪問節點,則圖中沒有循環。關於實施,首先嚐試,如果您遇到任何問題,請回過頭來解決問題。

+0

這隻適用於無向圖,但這就是汗說他有 – 2013-04-24 17:13:31

+0

從樣本看起來像一個無向圖的遍歷。但令人遺憾的是,簡單的谷歌搜索即將出現如此多的運行代碼,僞代碼,示例,這是令人難以置信的。那麼在尋求幫助之前嘗試了嗎? – abasu 2013-04-24 17:23:56

+0

我修改了我的代碼;它不起作用:( – mpluse 2013-04-24 19:36:52