数据结构_图(Graph)

       图(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.csdn.net/u011638883/article/details/17161407

      谢谢!!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值