1. 程式人生 > 實用技巧 >判斷圖是否為樹(java鄰接表實現)

判斷圖是否為樹(java鄰接表實現)

//實現 AbstractGraph<T>類以下對圖的操作,圖的鄰接表儲存。
//無向圖連通且無環則是樹
static int vcount=0;        //遍歷過的頂點數
public boolean isTree()//判斷無向圖 this 是否為一棵樹
{
    //訪問標記陣列,元素初值為false
    boolean[] visited=new boolean[this.vertexCount()];
    //father為遍歷頂點的父頂點,起點無父頂點,令初值為-1
    int father=-1;
    //只遍歷一條連通分量,若遍歷完vcount=圖總頂點數,則為連通圖
    boolean result=this.depth(0,visited,father);//result判斷是否有迴路
    if(vcount==this.vertexCount()) //判斷是否連通
    {
        vcount=0;
        return result;
    }
   vcount=0;
   return false;
}
private boolean depth(int i, boolean[] visited,int father)
{
    visited[i] = true;              //設定訪問標記
    vcount++;                       //遍歷過的頂點數加1
    //j依次獲得vi的所有鄰接頂點序號
    for (int j=this.next(i,-1); j!=-1; j=this.next(i,j))
    {
        if (!visited[j])         //若鄰接頂點vj未被訪問
        {
            father=i;            //vi為vj的父頂點
            if(!depth(j,visited,father))
                return false;
        }
        else if(j!=father)      //鄰接頂點vj已被訪問,且不是vi的父頂點,則有迴路
            return false;
    }
    return true;
}