日期:2014-05-19 浏览次数:20911 次
//演示程序:邻接矩阵表示的带权有向图(网)
import java.io.*;
//最大边数和顶点数
// “邻接矩阵”类
class Graph {
static int MaxEdges = 50;
static int MaxVertices = 10;
static double MaxValue=9999.9; //无穷大
//存放顶点的数组
private char VerticesList[]=new char[MaxVertices];
//邻接矩阵(存放两个顶点权值)
private double Edge[][]=new double[MaxVertices][MaxVertices];
private int CurrentEdges; //现有边数
private int CurrentVertices; //现有顶点数
//构造函数:建立空的邻接矩阵
public Graph ( ){
for ( int i = 0; i < MaxVertices; i++ )
for ( int j = 0; j < MaxVertices; j++ )
if(i==j)
Edge[i][j] = 0; //对角线
else //非对角线上无穷大
Edge[i][j] =MaxValue;
CurrentEdges = 0; //现有边数
CurrentVertices = 0; //现有顶点数
}
//查找指定的顶点的序号
public int FindVertex (char vertex){
//在顶点数组里面查找
for(int i=0;i<CurrentVertices;i++)
if(VerticesList[i]==vertex)
return i; //返回下标
return -1; //没有找到
}
//图空否?
public boolean IsGraphEmpty ( ){
return CurrentVertices==0;
}
//图满否?
public boolean IsGraphFull ( ){
return CurrentVertices==MaxVertices ||
CurrentEdges==MaxEdges;
}
//取得顶点数
public int NumberOfVertices ( ){
return CurrentVertices;
}
//取得边数
public int NumberOfEdges ( ){
return CurrentEdges;
}
//按序号取得顶点值
public char GetValue ( int i ){
return i >= 0 && i <= CurrentVertices-1
? VerticesList[i] : ' ';
}
//取得一条边的权值
public double GetWeight ( int v1, int v2 ){
if (v1 < 0 || v1 > CurrentVertices - 1)
return -1.0; //用-1表示出错
if (v2 < 0 || v2 > CurrentVertices - 1)
return -1.0;
return Edge[v1][v2];
}
//取得第一个邻接点的序号
public int GetFirstNeighbor ( int v ){
if (v< 0 || v > CurrentVertices - 1)
return -1; //用-1表示出错
//邻接矩阵的行号和列号是两个邻接点的序号
for ( int col = 0; col < CurrentVertices; col++ )
if ( Edge[v][col] > 0 && //自身
Edge[v][col] < MaxValue ) //无穷大
return col;
return -1; //无邻接点
}
//插入一个顶点
public int InsertVertex ( char vertex ){
if(IsGraphFull()) return -1; //插入失败
//顶点表增加一个元素
VerticesList[CurrentVertices]=vertex;
//邻接矩阵增加一行一列
for ( int j = 0;j <=CurrentVertices;j++ ) {
Edge[CurrentEdges][j]=MaxValue;
Edge[j][CurrentEdges]=MaxValue;
}
Edge[CurrentEdges][CurrentEdges]=0;
CurrentVertices++;
return CurrentVertices; //插入位置
}
//插入一个边
public boolean InsertEdge( int v1, int v2, double weight){
if (v1 < 0 || v1 > CurrentVertices - 1)
return false; //出错
if (v2 < 0 || v2 > CurrentVertices - 1)
return false;
Edge[v1][v2]=weight; //网,有向边
return true;
}
//删除一个顶点
public boolean RemoveVertex ( int v ){
if (v< 0 || v > CurrentVertices - 1)
return false; //出错
//修改顶点表
for(int i=v+1;i< CurrentVertices;i++)
VerticesList[i-1]=VerticesList[i];
//修改邻接矩阵
int k=0; //累计将要删去的边数
for(int i=0;i< CurrentVertices;i++)
if ( Edge[v][i] > 0 && //自身
Edge[v][i] < MaxValue ) //无穷大
k++; //第v行
for(int i=0;i< CurrentVertices;i++)
if ( Edge[i][v] > 0 &&am