Java学习(Day 16)

学习来源:日撸 Java 三百行(31-40天,图)_闵帆的博客-CSDN博客

整数矩阵及其运算

一、描述

在最开始的时候已经做过相关的工作, 只不过那会是面向过程的编码. 今天这里的步骤就是把面向过程改为面向对象.

  1. 矩阵对象的创建.

  2. getRows 等: getter, setter 在 java 里面很常用. 主要是为了访问控制.

  3. 整数矩阵的加法、乘法.

  4. Exception 的抛出与捕获机制.

  5. 用 this 调用其它的构造方法以减少冗余代码.

  6. getIdentityMatrix: 单位矩阵.

  7. resultMatrix.data[i][i]: 成员变量的访问权限: 在同一类里面是可以直接使用的.

二、具体代码

package matrix;

import java.util.Arrays;

/**
 * Int matrix. For efficiency we do not define ObjectMatrix. One can revise it
 * to obtain DoubleMatrix.
 * 
 * @author ShiHuai Wen shihuaiwen@outlook.com.
 */
public class IntMatrix {
	/**
	 * The data.
	 */
	int[][] data;

	/**
	 *********************
	 * The first constructor.
	 * 
	 * @param paraRows    The number of rows.
	 * @param paraColumns The number of columns.
	 *********************
	 */
	public IntMatrix(int paraRows, int paraColumns) {
		data = new int[paraRows][paraColumns];
	}// Of the first constructor

	/**
	 *********************
	 * The second constructor. Construct a copy of the given matrix.
	 * 
	 * @param paraMatrix The given matrix.
	 *********************
	 */
	public IntMatrix(int[][] paraMatrix) {
		data = new int[paraMatrix.length][paraMatrix[0].length];

		// Copy elements.
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[0].length; j++) {
				data[i][j] = paraMatrix[i][j];
			} // Of for j
		} // Of for i
	}// Of the second constructor

	/**
	 *********************
	 * The third constructor. Construct a copy of the given matrix.
	 * 
	 * @param paraMatrix The given matrix.
	 *********************
	 */
	public IntMatrix(IntMatrix paraMatrix) {
		this(paraMatrix.getData());
	}// Of the third constructor

	/**
	 *********************
	 * Get identity matrix. The values at the diagonal are all 1.
	 * 
	 * @param paraRows The given rows.
	 *********************
	 */
	public static IntMatrix getIdentityMatrix(int paraRows) {
		IntMatrix resultMatrix = new IntMatrix(paraRows, paraRows);
		for (int i = 0; i < paraRows; i++) {
			// According to access control, resultMatrix.data can be visited
			// directly.
			resultMatrix.data[i][i] = 1;
		} // Of for i
		return resultMatrix;
	}// Of getIdentityMatrix

	/**
	 *********************
	 * Overrides the method claimed in Object, the superclass of any class.
	 *********************
	 */
	public String toString() {
		return Arrays.deepToString(data);
	}// Of toString

	/**
	 *********************
	 * Get my data. Warning, the reference to the data instead of a copy of the data
	 * is returned.
	 * 
	 * @return The data matrix.
	 *********************
	 */
	public int[][] getData() {
		return data;
	}// Of getData

	/**
	 *********************
	 * Getter.
	 * 
	 * @return The number of rows.
	 *********************
	 */
	public int getRows() {
		return data.length;
	}// Of getRows

	/**
	 *********************
	 * Getter.
	 * 
	 * @return The number of columns.
	 *********************
	 */
	public int getColumns() {
		return data[0].length;
	}// Of getColumns

	/**
	 *********************
	 * Set one the value of one element.
	 * 
	 * @param paraRow    The row of the element.
	 * @param paraColumn The column of the element.
	 * @param paraValue  The new value.
	 *********************
	 */
	public void setValue(int paraRow, int paraColumn, int paraValue) {
		data[paraRow][paraColumn] = paraValue;
	}// Of setValue

	/**
	 *********************
	 * Get the value of one element.
	 * 
	 * @param paraRow    The row of the element.
	 * @param paraColumn The column of the element.
	 *********************
	 */
	public int getValue(int paraRow, int paraColumn) {
		return data[paraRow][paraColumn];
	}// Of getValue

	/**
	 *********************
	 * Add another matrix to me.
	 * 
	 * @param paraMatrix The other matrix.
	 *********************
	 */
	public void add(IntMatrix paraMatrix) throws Exception {
		// Step 1. Get the data of the given matrix.
		int[][] tempData = paraMatrix.getData();

		// Step 2. Size check.
		if (data.length != tempData.length) {
			throw new Exception(
					"Cannot add matrices. Rows not match: " + data.length + " vs. " + tempData.length + ".");
		} // Of if
		if (data[0].length != tempData[0].length) {
			throw new Exception(
					"Cannot add matrices. Rows not match: " + data[0].length + " vs. " + tempData[0].length + ".");
		} // Of if

		// Step 3. Add to me.
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[0].length; j++) {
				data[i][j] += tempData[i][j];
			} // Of for j
		} // Of for i
	}// Of add

	/**
	 *********************
	 * Add two existing matrices.
	 * 
	 * @param paraMatrix1 The first matrix.
	 * @param paraMatrix2 The second matrix.
	 * @return A new matrix.
	 *********************
	 */
	public static IntMatrix add(IntMatrix paraMatrix1, IntMatrix paraMatrix2) throws Exception {
		// Step 1. Clone the first matrix.
		IntMatrix resultMatrix = new IntMatrix(paraMatrix1);

		// Step 2. Add the second one.
		resultMatrix.add(paraMatrix2);

		return resultMatrix;
	}// Of add

	/**
	 *********************
	 * Multiply two existing matrices.
	 * 
	 * @param paraMatrix1 The first matrix.
	 * @param paraMatrix2 The second matrix.
	 * @return A new matrix.
	 *********************
	 */
	public static IntMatrix multiply(IntMatrix paraMatrix1, IntMatrix paraMatrix2) throws Exception {
		// Step 1. Check size.
		int[][] tempData1 = paraMatrix1.getData();
		int[][] tempData2 = paraMatrix2.getData();
		if (tempData1[0].length != tempData2.length) {
			throw new Exception("Cannot multiply matrices: " + tempData1[0].length + " vs. " + tempData2.length + ".");
		} // Of if

		// Step 2. Allocate space.
		int[][] resultData = new int[tempData1.length][tempData2[0].length];

		// Step 3. Multiply.
		for (int i = 0; i < tempData1.length; i++) {
			for (int j = 0; j < tempData2[0].length; j++) {
				for (int k = 0; k < tempData1[0].length; k++) {
					resultData[i][j] += tempData1[i][k] * tempData2[k][j];
				} // Of for k
			} // Of for j
		} // Of for i

		// Step 4. Construct the matrix object.
		IntMatrix resultMatrix = new IntMatrix(resultData);

		return resultMatrix;
	}// Of multiply

	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	public static void main(String args[]) {
		IntMatrix tempMatrix1 = new IntMatrix(3, 3);
		tempMatrix1.setValue(0, 1, 1);
		tempMatrix1.setValue(1, 0, 1);
		tempMatrix1.setValue(1, 2, 1);
		tempMatrix1.setValue(2, 1, 1);
		System.out.println("The original matrix is: " + tempMatrix1);

		IntMatrix tempMatrix2 = null;
		try {
			tempMatrix2 = IntMatrix.multiply(tempMatrix1, tempMatrix1);
		} catch (Exception ee) {
			System.out.println(ee);
		} // Of try
		System.out.println("The square matrix is: " + tempMatrix2);

		IntMatrix tempMatrix3 = new IntMatrix(tempMatrix2);
		try {
			tempMatrix3.add(tempMatrix1);
		} catch (Exception ee) {
			System.out.println(ee);
		} // Of try
		System.out.println("The connectivity matrix is: " + tempMatrix3);
	}// Of main
} // Of class IntMatrix

三、运行截图

图的连通性检测

一、描述

令图的连通矩阵为 M , M 0 = I M,M^0=I M,M0=I 为单位矩阵. 要知道图的连通性, 只需要计算 M a = M 0 + M 1 + . . . + M n − 1 M_a = M^0+M^1+...+M^{n-1} Ma=M0+M1+...+Mn1, 其中 n n n 是节点个数. M a M_a Ma中第 i i i行第 j j j 列元素为 0 的话, 就表示从节点 i i i到节点 j j j 不可达.

  1. 适用于有向图. 反正无向图是有向图的特殊形式.

  2. 0 次方的时候是单位矩阵.

  3. 为每一个方法写一个独立的测试方法. 测试代码有时比正常使用的代码更多.

  4. 第一个测试用例是无向图, 第二个是有向图. 可以看到, 后者从节点 1 不能到达节点 0.

  5. Matrix 基础代码准备好之后, 其它的算法真的很方便. 后面会进一步体会到其威力.

二、具体过程

1. 原理

M a = M 0 + M 1 + . . . + M n − 1 M_a = M^0+M^1+...+M^{n-1} Ma=M0+M1+...+Mn1 乍一看摸不着头脑. 这时候不妨把 M 2 M^2 M2拆开来看看.

对图中只有三个节点的矩阵来说
M i j 2 = M i 1 × M 1 j + M i 2 × M 2 j + M i 3 × M 3 j M^{2}_{ij} = M_{i1} \times M_{1j} + M_{i2} \times M_{2j} + M_{i3} \times M_{3j} Mij2=Mi1×M1j+Mi2×M2j+Mi3×M3j

下标表示某节点到某节点, 矩阵中的值若大于 0 则表示可两点可达
M 21 M_{21} M21 为大于 1 的值则表示 2 节点到 1 节点可达.

而 $M^2 M^3 M^4 $ … 这些的指数就表示需要经过 1 2 3 … 个节点使得两节点连接.

2. 具体代码

package datastructure.graph;

import matrix.IntMatrix;

/**
 * Directed graph. Note that undirected graphs are a special case of directed
 * graphs.
 * 
 * @author ShiHuai Wen shihuaiwen@outlook.com.
 */
public class Graph {
	/**
	 * The connectivity matrix.
	 */
	IntMatrix connectivityMatrix;

	/**
	 *********************
	 * The first constructor.
	 * 
	 * @param paraNumNodes The number of nodes in the graph.
	 *********************
	 */
	public Graph(int paraNumNodes) {
		connectivityMatrix = new IntMatrix(paraNumNodes, paraNumNodes);
	}// Of the first constructor

	/**
	 *********************
	 * The second constructor.
	 * 
	 * @param paraMatrix The data matrix.
	 *********************
	 */
	public Graph(int[][] paraMatrix) {
		connectivityMatrix = new IntMatrix(paraMatrix);
	}// Of the second constructor

	/**
	 *********************
	 * Overrides the method claimed in Object, the superclass of any class.
	 *********************
	 */
	public String toString() {
		String resultString = "This is the connectivity matrix of the graph.\r\n" + connectivityMatrix;
		return resultString;
	}// Of toString

	/**
	 *********************
	 * Get the connectivity of the graph.
	 * 
	 * @throws Exception for internal error.
	 *********************
	 */
	public boolean getConnectivity() throws Exception {
		// Step 1. Initialize accumulated matrix: M_a = I.
		IntMatrix tempConnectivityMatrix = IntMatrix.getIdentityMatrix(connectivityMatrix.getData().length);

		// Step 2. Initialize M^1.
		IntMatrix tempMultipliedMatrix = new IntMatrix(connectivityMatrix);

		// Step 3. Determine the actual connectivity.
		for (int i = 0; i < connectivityMatrix.getData().length - 1; i++) {
			// M_a = M_a + M^k
			tempConnectivityMatrix.add(tempMultipliedMatrix);

			// M^k
			tempMultipliedMatrix = IntMatrix.multiply(tempMultipliedMatrix, connectivityMatrix);
		} // Of for i

		// Step 4. Check the connectivity.
		System.out.println("The connectivity matrix is: " + 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("Node " + i + " cannot reach " + j);
					return false;
				} // Of if
			} // Of for j
		} // Of for i

		return true;
	}// Of getConnectivity

	/**
	 *********************
	 * Unit test for getConnectivity.
	 *********************
	 */
	public static void getConnectivityTest() {
		// Test an undirected graph.
		int[][] tempMatrix = { { 0, 1, 0 }, { 1, 0, 1 }, { 0, 1, 0 } };
		Graph tempGraph2 = new Graph(tempMatrix);
		System.out.println(tempGraph2);

		boolean tempConnected = false;
		try {
			tempConnected = tempGraph2.getConnectivity();
		} catch (Exception ee) {
			System.out.println(ee);
		} // Of try.

		System.out.println("Is the graph connected? " + tempConnected);

		// Test a directed graph.
		// Remove one arc to form a directed graph.
		tempGraph2.connectivityMatrix.setValue(1, 0, 0);

		tempConnected = false;
		try {
			tempConnected = tempGraph2.getConnectivity();
		} catch (Exception ee) {
			System.out.println(ee);
		} // Of try.

		System.out.println("Is the graph connected? " + tempConnected);
	}// Of getConnectivityTest

	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	public static void main(String args[]) {
		System.out.println("Hello!");
		Graph tempGraph = new Graph(3);
		System.out.println(tempGraph);

		// Unit test.
		getConnectivityTest();
	}// Of main

} // Of class Graph

3. 运行截图

总结

矩阵连通性那个判断真的是太神奇了, 无论如何我都想不到能利用矩阵相乘来判断. 在以往的经验中我能想到的就是深度优先遍历和广度优先遍历.

这几天才深深感觉到数学才是计算机的基础, 尤其是千变万化的矩阵.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值