图的存储结构(邻接矩阵方式)
此图为带权无向图
public class MyGraph {
private ArrayList
测试类
测试图如图所示:
测试程序如下:
//顶点数为4
int n = 4;
String[] vertex = {"A","B","C","D"};
MyGraph graph = new MyGraph(n);
for (String string : vertex) {
graph.insertVertex(string);
}
graph.insertEdge(0, 1, 3);
graph.insertEdge(0, 2, 8);
graph.insertEdge(0, 3,10);
graph.insertEdge(1, 2, 6);
System.out.println("结点数:"+graph.getNumOfVertex());
System.out.println("边数:"+graph.getNumofEdges());
System.out.println("删除前的邻接矩阵:");
graph.printEdges();
graph.deleteEdge(1, 2);
System.out.println("删除边后:");
System.out.println("结点个数为:"+graph.getNumOfVertex());
System.out.println("边数为:"+graph.getNumofEdges());
System.out.println("删除后的邻接矩阵:");
graph.printEdges();
测试结果:
遍历算法
测试图(由于权值不影响遍历结果,所以不标注):
深度优先
//邻接矩阵的深度遍历操作
public void DFSTraverse(MyGraph graph) {
for (int i = 0; i < graph.getNumOfVertex(); i++) {
visited[i] = false;
}
for( int i = 0; i < graph.getNumOfVertex(); i++) {
//对未访问过的结点调用DFS,若是连通图,只会执行一次,非连通图的话有多少个子图则会调用多少次
if (!visited[i]) {
DFS(graph, i);
}
}
}
//邻接矩阵的深度优先递归算法
public void DFS(MyGraph graph, int i) {
//设置访问标志位为true
visited[i] = true;
System.out.print(getValueByIndex(i)+" ");
for(int j = 0; j < graph.getNumOfVertex(); j++) {
if (edges[i][j] != 0 && edges[i][j] != INF && !visited[j] ) {
//对未访问的邻接结点递归调用
DFS(graph, j);
}
}
}
广度优先
//邻接矩阵的广度遍历算法
public void BFSTraverse(MyGraph graph) {
int i,j;
//初始化访问标志矩阵
for(i = 0; i < graph.getNumOfVertex(); i++) {
visited[i] = false;
}
//使用linkedList模拟队列的功能
LinkedList queue = new LinkedList<>();
for(i = 0; i < graph.getNumOfVertex(); i++) {
//该图为非连通图时,第一次广度遍历完后还有结点未被访问时会再次进入这个分支
//该图为连通图时,该分支只会执行一次,因为执行一次后所有的结点都被访问到了
if (!visited[i]) {
visited[i] = true;
System.out.print(getValueByIndex(i)+" ");
//将结点添加到队尾
queue.addLast(i);
while(!queue.isEmpty()) {
//移除队头元素并将其赋值给i
i = ((Integer)queue.removeFirst()).intValue();
for(j = 0; j < graph.getNumOfVertex(); j++) {
if (edges[i][j] != 0 && edges[i][j] != INF && !visited[j] ) {
visited[j] = true;
System.out.print(getValueByIndex(j)+" ");
queue.addLast(j);
}
}
}
}
}
}
广度优先各结点在队列中的情况如下
测试程序:
public class GraphTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//顶点数为4
int n = 9;
String[] vertex = {"A","B","C","D","E","F","G","H","I"};
MyGraph graph = new MyGraph(n);
for (String string : vertex) {
graph.insertVertex(string);
}
graph.insertEdge(0, 1, 3);
graph.insertEdge(0, 2, 8);
graph.insertEdge(1, 3,10);
graph.insertEdge(1, 4, 3);
graph.insertEdge(2, 5, 3);
graph.insertEdge(2, 6, 3);
graph.insertEdge(3, 7, 3);
graph.insertEdge(7, 8, 3);
System.out.println("深度优先遍历结果:");
graph.DFSTraverse(graph);
System.out.println("\n广度优先遍历:");
graph.BFSTraverse(graph);
}
}
测试结果: