一、实验目的
1、熟练掌握图的邻接矩阵和邻接表存储结构;
2、掌握图的创建方法;
3、掌握求顶点度的方法;
4、掌握图的深度优先和广度优先遍历方法;
二、实验内容
1、分别定义图的邻接矩阵和邻接表存储结构;
2、分别在两种存储结构下根据输入的顶点和边(或弧)创建图;
3、分别在两种存储结构下实现求顶点度的操作;
3、分别在两种存储结构下实现图的深度和广度优先遍历算法。
三、实验环境
Eclipse环境或C++编程环境
四、实验步骤
1、定义图的存储结构
2、实现图的创建方法,并创建一个如下的图:
3、实现求第一个邻接点firstAdjVex()和下一个邻接点nextAdjVex()的操作;
4、写一个算法,求各个顶点的度;
5、对创建的图进行深度优先和广度优先遍历。
定义图的两种存储结构:邻接矩阵和邻接表
邻接表:
节点类:
class VNode{
public Object data;
public ArcNode firstArc;
public VNode() {
this.data=null;
this.firstArc=null;
}
public VNode(Object data) {
//VNode构造方法
this.data=data;
this.firstArc=null;
}
public VNode(Object data,ArcNode firstArc) {
this.data=data;
this.firstArc=firstArc;
}
}
class ArcNode{
public int adjVex;
ArcNode nextArc;
public int weight;
public ArcNode() {
//ArcNode构造方法
this.adjVex=-1;
this.nextArc=null;
this.weight=0;
}
public ArcNode(int adjVex) {
this.adjVex=adjVex;
this.nextArc=null;
this.weight=0;
}
public ArcNode(int adjVex,int weight) {
this.adjVex=adjVex;
this.nextArc=null;
this.weight=weight;
}
public ArcNode(int adjVex,ArcNode nextArc,int weight) {
this.adjVex=adjVex;
this.nextArc=nextArc;
this.weight=weight;
}
}
方法:
package shiyan3;
import shiyan2.*;
//import java.util.Queue;
import java.util.Scanner;
class VNode{
public Object data;
public ArcNode firstArc;
public VNode() {
this.data=null;
this.firstArc=null;
}
public VNode(Object data) {
//VNode构造方法
this.data=data;
this.firstArc=null;
}
public VNode(Object data,ArcNode firstArc) {
this.data=data;
this.firstArc=firstArc;
}
}
class ArcNode{
public int adjVex;
ArcNode nextArc;
public int weight;
public ArcNode() {
//ArcNode构造方法
this.adjVex=-1;
this.nextArc=null;
this.weight=0;
}
public ArcNode(int adjVex) {
this.adjVex=adjVex;
this.nextArc=null;
this.weight=0;
}
public ArcNode(int adjVex,int weight) {
this.adjVex=adjVex;
this.nextArc=null;
this.weight=weight;
}
public ArcNode(int adjVex,ArcNode nextArc,int weight) {
this.adjVex=adjVex;
this.nextArc=nextArc;
this.weight=weight;
}
}
public class ALGragh implements IGragh{
private VNode vexs[];
private int vexNum;
private int arcNum;
public ALGragh() {
this.vexNum=0;
this.arcNum=0;
this.vexs=null;
}
public ALGragh(int vexNum,int arcNum,VNode[] vexs) {
this.vexNum = vexNum;
this.arcNum = arcNum;
this.vexs = vexs;
}
public void createDG() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入图的顶点数和边数:");
vexNum = sc.nextInt();
arcNum = sc.nextInt();
vexs = new VNode[vexNum];
System.out.println("请输入图的各顶点值:");
for(int i=0;i<vexNum;i++) {
vexs[i] = new VNode(sc.next());
}
System.out.println("请输入各边:");
for(int j=0