樹結構有一個基本的特點就是數據元素之間有層的關係,每一層的元素可以和多個下層元素關聯,但是隻能和一個上層元素關聯。如果擴展一下,每個數據元素之間可以任意聯繫,這就構成了一個圖結構,研究圖結構的一個專門理論就是圖論。
圖的構成:
頂點(Vertex):圖中的數據元素。
邊(Edge):圖中連接這些頂點的線。
具體的圖的相關結構不再贅述,自行百度。
1.數據準備
class GraphMatrix
{ static final int MaxNum=20;
static final int MaxValue=65535;
char[] Vertex=new char[MaxNum]; //保存頂點信息(序號或字母)
int GType; //圖的類型(0:無向圖,1:有向圖)
int VertexNum; //頂點的數量
int EdgeNum; //邊的數量
int[][] EdgeWeight=new int[MaxNum][MaxNum]; //保存邊的權
int[] isTrav=new int[MaxNum]; //遍歷標誌
}
2.創建圖
static void CreateGraph(GraphMatrix GM) //創建鄰接矩陣圖
{
int i,j,k;
int weight; //權
char EstartV,EendV; //邊的起始頂點
System.out.printf("輸入圖中各頂點信息\n");
for(i=0;i<GM.VertexNum;i++) //輸入頂點
{
System.out.printf("第%d個頂點:",i+1);
GM.Vertex[i]=(input.next().toCharArray())[0]; //保存到各頂點數組元素中
}
System.out.printf("輸入構成各邊的頂點及權值:\n");
for(k=0;k<GM.EdgeNum;k++) //輸入邊的信息
{
System.out.printf("第%d條邊:",k+1);
EstartV=input.next().charAt(0);
EendV=input.next().charAt(0);
weight=input.nextInt();
for(i=0;EstartV!=GM.Vertex[i];i++); //在已有頂點中查找始點
for(j=0;EendV!=GM.Vertex[j];j++); //在已有頂點中查找結終點
GM.EdgeWeight[i][j]=weight; //對應位置保存權值,表示有一條邊
if(GM.GType==0) //若是無向圖
{
GM.EdgeWeight[j][i]=weight; //在對角位置保存權值
}
}
}
3.清空圖
static void ClearGraph(GraphMatrix GM)
{
int i,j;
for(i=0;i<GM.VertexNum;i++) //清空矩陣
{
for(j=0;j<GM.VertexNum;j++)
{
GM.EdgeWeight[i][j]=GraphMatrix.MaxValue; //設置矩陣中各元素的值爲MaxValue
}
}
}
4.顯示圖(鄰接矩陣)
static void OutGraph(GraphMatrix GM) //輸出鄰接矩陣
{
int i,j;
for(j=0;j<GM.VertexNum;j++)
{
System.out.printf("\t%c",GM.Vertex[j]); //在第1行輸出頂點信息
}
System.out.printf("\n");
for(i=0;i<GM.VertexNum;i++)
{
System.out.printf("%c",GM.Vertex[i]);
for(j=0;j<GM.VertexNum;j++)
{
if(GM.EdgeWeight[i][j]==GraphMatrix.MaxValue) //若權值爲最大值
{
System.out.printf("\tZ"); //以Z表示無窮大
}
else
{
System.out.printf("\t%d",GM.EdgeWeight[i][j]); //輸出邊的權值
}
}
System.out.printf("\n");
}
}
5.圖的遍歷(深度優先)
static void DeepTraGraph(GraphMatrix GM) //深度優先遍歷
{
int i;
for(i=0;i<GM.VertexNum;i++) //清除各頂點遍歷標誌
{
GM.isTrav[i]=0;
}
System.out.printf("深度優先遍歷結點:");
for(i=0;i<GM.VertexNum;i++)
{
if(GM.isTrav[i]==0) //若該點未遍歷
{
DeepTraOne(GM,i); //調用函數遍歷
}
}
System.out.printf("\n");
}
public static void main(String[] args) {
GraphMatrix GM=new GraphMatrix(); //定義保存鄰接表結構的圖
System.out.printf("輸入生成圖的類型:");
GM.GType=input.nextInt(); //圖的種類
System.out.printf("輸入圖的頂點數量:");
GM.VertexNum=input.nextInt(); //輸入圖頂點數
System.out.printf("輸入圖的邊數量:");
GM.EdgeNum=input.nextInt(); //輸入圖邊數
ClearGraph(GM); //清空圖
CreateGraph(GM); //生成鄰接表結構的圖
System.out.printf("該圖的鄰接矩陣數據如下:\n");
OutGraph(GM); //輸出鄰接矩陣
DeepTraGraph(GM); //深度優先搜索遍歷圖
}
}
圖的數據結構到此爲止了。