图(Graph)是为了模拟解决一类现实中的问题的而设计的数据结构,个人觉得相对于二叉搜索树,它并没有什么算法操作的的优势,只是它可以很好的模拟显示中的图问题。图的表示可以用邻接矩阵和邻接表来表示,本文就使用邻接矩阵的方法实现了一下简单的无向图。
package com.wly.algorithmbase.datastructure;
/**
* 无向图
* @author wly
*
*/
public class NoDirectionGraph {
private int MAX_SIZE = 10; //图中包含的最大顶点数
private Vertex[] vertexList; //顶点数组
private int[][] indicatorMat; //指示顶点之间的连通关系的邻接矩阵
private int nVertex; //当前实际保存的顶点数目
public NoDirectionGraph() {
vertexList = new Vertex[MAX_SIZE];
indicatorMat = new int[MAX_SIZE][MAX_SIZE];
nVertex = 0;
//初始化邻接矩阵元素为0
for(int j=0;j<MAX_SIZE;j++) {
for(int k=0;k<MAX_SIZE;k++) {
indicatorMat[j][k] = 0;
}
}
}
public void addVertex(Vertex v) {
if(nVertex < MAX_SIZE) {
vertexList[nVertex++] = v;
} else {
System.out.println("---插入失败,顶点数量已达上限!");
}
}
/**
* 修改邻接矩阵,添加新的边
* @param start
* @param end
*/
public void addEdge(int start,int end) {
indicatorMat[start][end] = 1;
indicatorMat[end][start] = 1;
}
/**
* 打印邻接矩阵
*/
public void printIndicatorMat() {
for(int[] line:indicatorMat) {
for(int i:line) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
/**
* 图中的顶点类
* @author wly
*
*/
class Vertex {
String name;
public Vertex(String name) {
this.name = name;
}
}
测试一下:
package com.wly.algorithmbase.datastructure;
public class Test {
public static void main(String[] args) {
NoDirectionGraph graph = new NoDirectionGraph();
graph.addVertex(new Vertex("A"));
graph.addVertex(new Vertex("B"));
graph.addVertex(new Vertex("C"));
graph.addVertex(new Vertex("D"));
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 3);
graph.printIndicatorMat();
}
}
运行结果:
0 1 1 0 0 0 0 0 0 0
1 0 0 1 0 0 0 0 0 0
1 0 0 1 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
这里描述了如下的图结构:
O啦~~~
转载请保留出处:http://blog.youkuaiyun.com/u011638883/article/details/17161407
谢谢!!