图的邻接矩阵类实现


//图类
public class Graphic {
	//结点数组 二维数组
	ArrayList nodes = new ArrayList();//结点数组
	int[][] edges ;//图的二维数组
	int unget =-1;// 节点之间没有连接的默认值
	int numOfedges;//边的数量
	
	
	public Graphic(int n) {
		edges = new int[n][n];
		for(int i=0;i this.nodes.size()) || (v2<0 || v2 > this.nodes.size()) || (v1 == v2)){
			throw new Exception("v1或者v2参数有误");
		}
		
		edges[v1][v2] = weight;
		numOfedges++;
	}
	
	//删除某两个结点之间的边
	public void deleteEdge(int v1, int v2) throws Exception{
		if((v1<0 || v1 > this.nodes.size()) || (v2<0 || v2 > this.nodes.size()) || (v1 == v2)){
			throw new Exception("v1或者v2参数有误");
		}
		
		if(edges[v1][v2] == unget){
			throw new Exception("结点之间的边已经是不可用状态,无法再删除");
		}
		
		edges[v1][v2] = unget;
		numOfedges--;
	}
	
	public  static  void printAll(Graphic gra){
		int[][] model = gra.edges;
		int size = model.length;
		
		for(int i=0;in||weights[i].v2>n){
				throw new Exception("边中选定的节点数大于实际的节点数");
			}
			gra.insertEdge(weights[i].v1, weights[i].v2, weights[i].weight);
		}
	}
}

//测试类
public class Test {
	
	
	public static void main(String[] args){
		//我们需要2个数组:1.第1个是结点数组,2.第二个是Weight的数组(边相关)
		Object[] nodes  = new Object[]{1,2,3,4,5};
		Weight w1 = new Weight(0, 1, 100);
		Weight w2 = new Weight(1, 2, 200);
		Weight w3 = new Weight(2, 3, 300);
		Weight w4 = new Weight(3, 4, 400);
		Weight w5 = new Weight(4, 0, 500);
		//构造节点数组a
		Weight[] weights = new Weight[]{w1,w2,w3,w4,w5};
		
		//我们要生成的图对象
		Graphic gra = new Graphic(nodes.length);
		try {
			Weight.createGraphic(gra, nodes, weights);
			Graphic.printAll(gra);
			System.out.println("边的个数为:"+gra.numOfedges);
			System.out.println("结点的个数为:"+gra.numOfNode());
			//删除边
			gra.deleteEdge(4, 0);
			System.out.println("删除了某边之后的图");
			Graphic.printAll(gra);
			System.out.println("边的个数为:"+gra.numOfedges);
			System.out.println("结点的个数为:"+gra.numOfNode());

			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}	
//测试结果
0 100 -1 -1 -1 
-1 0 200 -1 -1 
-1 -1 0 300 -1 
-1 -1 -1 0 400 
500 -1 -1 -1 0 
边的个数为:5
结点的个数为:5
删除了某边之后的图
0 100 -1 -1 -1 
-1 0 200 -1 -1 
-1 -1 0 300 -1 
-1 -1 -1 0 400 
-1 -1 -1 -1 0 
边的个数为:4
结点的个数为:5




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值