20.无向图邻接矩阵类
namespace DSList
{
//无向图邻接矩阵类(Undirected Graph Adjacency Matrix Class)
public class GraphAdjMatrix<T> : IGraph<T>
{
//Fields
private GvNode<T>[] nodes; //vertex array
private int numEdges; //Edges number
private int[,] matrix; //Matrix array
//Constructor
public GraphAdjMatrix(int n)
{
nodes = new GvNode<T>[n];
matrix = new int[n, n];
numEdges = 0;
}
//Properties
public GvNode<T> GetGvNode(int index)
{
return nodes[index];
}
public void SetGvNode(int index, GvNode<T> v)
{
nodes[index] = v;
}
public int NumEdges
{
get
{
return numEdges;
}
set
{
numEdges = value;
}
}
public int GetMatrix(int index1, int index2)
{
return matrix[index1, index2];
}
public void SetMatrix(int index1, int index2)
{
matrix[index1, index2] = 1;
}
//Base methods
public int GetNumOfVertex()
{
return nodes.Length;
}
public int GetNumOfEdge()
{
return numEdges;
}
public bool IsGvNode(GvNode<T> v)
{
foreach (GvNode<T> nd in nodes)
{
if (v.Equals(nd))
{
return true;
}
}
return false;
}
public int GetIndex(GvNode<T> v)
{
int i = -1;
for (i = 0; i < nodes.Length; ++i)
{
if (nodes[i].Equals(v))
{
return i;
}
}
return i;
}
public void SetEdge(GvNode<T> v1, GvNode<T> v2,int v)
{
if (!IsGvNode(v1) || !IsGvNode(v2))
{
Console.WriteLine("GvNode is not belong to Graph!");
return;
}
if (v == 1)
{
matrix[GetIndex(v1), GetIndex(v2)] = v;
matrix[GetIndex(v2), GetIndex(v1)] = v;
++numEdges;
}
else
{
Console.WriteLine("Weight is not right!");
}
}
public void DelEdge(GvNode<T> v1, GvNode<T> v2)
{
if (!IsGvNode(v1) || !IsGvNode(v2))
{
Console.WriteLine("GvNode is not belong to Graph!");
return;
}
if (matrix[GetIndex(v1), GetIndex(v2)] == 1)
{
matrix[GetIndex(v1), GetIndex(v2)] = 0;
matrix[GetIndex(v2), GetIndex(v1)] = 0;
--numEdges;
}
else
{
Console.WriteLine("Edge is not existent!");
return;
}
}
public bool IsEdge(GvNode<T> v1, GvNode<T> v2)
{
if (!IsGvNode(v1) || !IsGvNode(v2))
{
Console.WriteLine("GvNode is not belong to Graph!");
return false;
}
if (matrix[GetIndex(v1), GetIndex(v2)] == 1)
{
return true;
}
else
{
return false;
}
}
}
}