1 . 创建图的邻接矩阵数据结构
public class MGraph {
/*图的邻接矩阵表示*/
int vexs; //图中结点数目
char data[]; //存放结点数据
int [][]weight; //存放边
public MGraph(int ve){
vexs=ve;
data=new char[ve];
weight=new int[ve][ve];
}
}
2 . 创建图的邻接矩阵,显示邻接矩阵,实现图的深度遍历
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class GraphMetrix {
/*图的邻接矩阵表示,各中操作*/
/*创建图的邻接矩阵*/
public void CreateGraph(MGraph graph,int vexs,char data[],int [][]weight){
int i,j;
for(i=0;i<vexs;i++){
graph.data[i]=data[i];
for(j=0;j<vexs;j++){
graph.weight[i][j]=weight[i][j];
}
}
}
/*显示图的邻接矩阵*/
public void ShowGraph(MGraph graph){
int vexs=graph.vexs;
int [][]weight=graph.weight;
int i,j;
for(i=0;i<vexs;i++){
System.out.print(graph.data[i]+":");
for(j=0;j<vexs;j++){
System.out.print(weight[i][j]+" ");
}
System.out.println();
}
}
/*获取当前顶点K的第一个邻接顶点位置*/
public int GetFirst(MGraph graph,int k){
int i;
if(k<0||k>graph.vexs-1){
System.out.println("参数k值超出范围");
return -1;
}
for(i=0;i<graph.vexs;i++){
if(graph.weight[k][i]==1)
return i;
}
return -1;
}
/*获取当前顶点K的第t个邻接顶点下一个邻接顶点的位置*/
public int GetNext(MGraph graph,int k,int t){
int i;
if(k<0||k>graph.vexs-1||t<0||t>graph.vexs-1){
System.out.println("参数k或t值超出范围");
return -1;
}
for(i=t+1;i<graph.vexs;i++){
if(graph.weight[k][i]==1)
return i;
}
return -1;
}
/*递归方式深度优先遍历图的邻接矩阵*/
public void DFSVGraph(MGraph graph,int k,int visited[]){
/*graph为图的邻接矩阵表示,k为起始顶点,visited[]为访问过标记数组*/
int u; //k的邻接顶点
System.out.print(graph.data[k]+", ");
visited[k]=1;//表示顶点k被访问过
u=GetFirst(graph,k);//获取k的第一个邻接顶点u
while(u!=-1){
if(visited[u]==0){ //如果u未被访问过,则递归访问u的邻接点
DFSVGraph(graph,u,visited);
}
u=GetNext(graph,k,u);//获取k的下一个邻接顶点
}
}
/*广度优先遍历图的邻接矩阵*/
public void BFSVGraph(MGraph graph,int k,int visited[]){
/*graph为图的邻接矩阵表示,k为起始顶点,visited[]为访问过标记数组*/
Queue <Integer>queue=new LinkedList <Integer>();
int u;
queue.add(k);//顶点k进入队列
visited[k]=1;//顶点k标记被访问过
while(!queue.isEmpty()){
u=queue.remove();//取出队列顶元素
System.out.print(graph.data[u]+", ");
int v=GetFirst(graph,u);//获取u的第一个邻接顶点v
while(v!=-1){
if(visited[v]==0){ //如果v未被访问过,则递归访问v的邻接点
queue.add(v);
visited[v]=1;//顶点v标记被访问过
}
v=GetNext(graph,u,v);//获取u的下一个邻接顶点
}
}
}
public static void main(String args[]){
char []data=new char[]{'A','B','C','D','E'};
int vexs=data.length;
int visited[]=new int [vexs];/*定义访问标记数组*/
int [][]weight=new int[][]{
{0,1,0,0,1},
{1,0,1,1,0},
{0,1,0,0,0},
{0,1,0,0,1},
{1,0,0,1,0}
};
for(int i=0;i<vexs;i++){
/*初始化访问标记数组*/
visited[i]=0;
}
MGraph graph=new MGraph(vexs);
GraphMetrix gam=new GraphMetrix();
gam.CreateGraph(graph,vexs,data,weight);
gam.ShowGraph(graph);
//gam.DFSVGraph(graph, 0, visited);
gam.BFSVGraph(graph, 0, visited);
}
}