java学习第32天,图的连通性检测

1,适用于有向图. 反正无向图是有向图的特殊形式。
2,0次方的时候是单位矩阵。
3,为每一个方法写一个独立的测试方法,测试代码有时比正常使用的代码更多。
4,第一个测试用例是无向图,第二个是有向图。可以看到,后者从节点1不能到达节点0。
5,Matrix基础代码准备好之后,其它的算法真的很方便。

package java31to40;

public class D32_Graph {
	D31_IntMatrix connectivityMatrix;

	public static void main(String[] args) {
		System.out.println("Hello!");
		D32_Graph tempGraph = new D32_Graph(3);
		System.out.println(tempGraph);
		getConnectivityTest();
	}

	public D32_Graph(int paraNumNodes) {
		connectivityMatrix = new D31_IntMatrix(paraNumNodes, paraNumNodes);
	}

	public D32_Graph(int[][] paraMatrix) {
		connectivityMatrix = new D31_IntMatrix(paraMatrix);
	}

	public String toString() {
		String resultString = "图的连通性矩阵.\r\n" + connectivityMatrix;
		return resultString;
	}

	public boolean getConnectivity() throws Exception {
		D31_IntMatrix tempConnectivityMatrix = D31_IntMatrix.getIdentityMatrix(connectivityMatrix.getData().length);
		D31_IntMatrix tempMultipliedMatrix = new D31_IntMatrix(connectivityMatrix);
		for (int i = 0; i < connectivityMatrix.getData().length - 1; i++) {
			tempConnectivityMatrix.add(tempMultipliedMatrix);
			tempMultipliedMatrix = D31_IntMatrix.multiply(tempMultipliedMatrix, connectivityMatrix);
		}
		System.out.println("连通性矩阵为: " + tempConnectivityMatrix);
		int[][] tempData = tempConnectivityMatrix.getData();
		for (int i = 0; i < tempData.length; i++) {
			for (int j = 0; j < tempData.length; j++) {
				if (tempData[i][j] == 0) {
					System.out.println("节点 " + i + " 不能到达 " + j);
					return false;
				}
			}
		}
		return true;
	}

	public static void getConnectivityTest() {
		int[][] tempMatrix = { { 0, 1, 0 }, { 1, 0, 1 }, { 0, 1, 0 } };
		D32_Graph tempGraph2 = new D32_Graph(tempMatrix);
		System.out.println(tempGraph2);
		boolean tempConnected = false;
		try {
			tempConnected = tempGraph2.getConnectivity();
		} catch (Exception ee) {
			System.out.println(ee);
		}
		System.out.println("图是否具有连通性? " + tempConnected);
		tempGraph2.connectivityMatrix.setValue(1, 0, 0);
		tempConnected = false;
		try {
			tempConnected = tempGraph2.getConnectivity();
		} catch (Exception ee) {
			System.out.println(ee);
		}
		System.out.println("图是否具有连通性? " + tempConnected);
	}
}

结果输出:

Hello!
图的连通性矩阵.
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
图的连通性矩阵.
[[0, 1, 0], [1, 0, 1], [0, 1, 0]]
连通性矩阵为: [[2, 1, 1], [1, 3, 1], [1, 1, 2]]
图是否具有连通性? true
连通性矩阵为: [[1, 1, 1], [0, 2, 1], [0, 1, 2]]
节点 1 不能到达 0
图是否具有连通性? false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值