无权无向图、带权无向图的实现 java
邻接矩阵实现无权无向图、带权无向图 java
1.图的接口
import java.util.List;
public interface Graph {
public int getSize(); //返回图中的顶点数
public List getVertices(); //返回图形中的顶点
public V getVertex(int index) throws Exception; //返回指定顶点索引的对象
public int getIndex(V v); //返回指定顶点对象的索引
public List getNeighbors(int index) throws Exception; //使用指定的索引返回顶点的邻居
public int getDegree(int v) throws Exception; //返回指定顶点的度数
public void printEdges(); //打印边缘
public void clear(); //清除图形
public void addVertex(V vertex); //在图形中添加一个顶点
public void addEdge(int u,int v); //为图形添加边缘
public AbstractGraph.Tree dfs(int v); //获取深度优先搜索树
public AbstractGraph.Tree bfs(int v); //获得广度优先搜索树
}
2.无权无向图
import java.util.*;
public class UnweightedUndirectedGraph implements Graph {
public final static int INFINITY = Integer.MAX_VALUE;
private int vexNum,arcNum; //当前顶点数和边数
private V[] vexs; //顶点
private int[][] arcs; //邻接矩阵
public UnweightedUndirectedGraph(){
}
public UnweightedUndirectedGraph(int vexNum,int arcNum,V[] vexs,int[][] arcs){
this.vexNum = vexNum;
this.arcNum = arcNum;
this.vexs = vexs;
this.arcs = arcs;
}
public void createWUG(){
Scanner in = new Scanner(System.in);
System.out.println("请输入图的顶点数和图的边数:");
vexNum = in.nextInt();
arcNum = in.nextInt();
vexs = (V[])new Object[vexNum];
System.out.println("请输入图的各个顶点:");
for(int v = 0;v < vexNum;v++){
vexs[v] = (V)in.next();
}
arcs = new int[vexNum][vexNum];
for(int v = 0;v < vexNum;v++){
for(int u = 0;u < vexNum;u++){
arcs[v][u] = INFINITY;
}
}
System.out.println("请输入各个边的两个顶点:");
for(int k = 0;k < arcNum;k++){
int v = locateVex(in.next());
int u = locateVex(in.next());
arcs[v][u] = arcs[u][v] = 1;
}
}
public int locateVex(Object vex){
for(int v = 0;v < vexNum;v++){
if(vexs[v].equals(vex)){
return v;
}
}
return -1;
}
@Override
public int getSize() { //返回图中的顶点数
return vexNum;
}
@Override
public List getVertices() { //返回图形中的顶点
List<V> Vex = new ArrayList<V>(Arrays.asList(vexs));
return Vex;
}
@Override
public V getVertex(int index) throws Exception { //返回指定顶点索引的对象
if(index < 0 || index >= vexNum){
throw new Exception("第" + index + "个顶点不存在");
}
return vexs[index];
}
@Override
public int getIndex(Object o) { //返回指定顶点对象的索引