1.数组与矩阵
2.稀疏矩阵二维数组被称为矩阵,A[m][n]表示m行n列的矩阵
线性代数学的不能再烂了,数据结构中注意,题目给出的矩阵第一个元素是a[0][0]还是a[1][1]
矩阵可以按按行优先存储和按列优先存储
矩阵的基本运算,如转置、矩阵加减、矩阵相乘等翻线性代数的书,代码实现照着翻译成设计语言即可
系统元素或者零元素在矩阵中的分布存在一定规律的矩阵称为特殊矩阵,反之是稀疏矩阵
国外普遍的看法是:矩阵中绝大多数元素都为0的矩阵称为稀疏矩阵
3.稀疏矩阵的存储及相关操作
1)三元组表示法
package matrix.trimat;
import java.util.Arrays;
//矩阵
@SuppressWarnings("unused")
public class Matrix {
//三元组
private class Trimat{
int val;//元素值
int i,j;//行号和列号
}
private Trimat trimat;//矩阵属性,三元组存储
//创建矩阵,用三元表存储
public Matrix(int[][] A){
int m = A.length;//行
int n = A[0].length;//列
Trimat[] trimat = new Trimat[1];
int k = 1;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
//按行优先顺序存储非零元素
if(A[i][j] != 0){
trimat = Arrays.copyOf(trimat, trimat.length + 1);
trimat[trimat.length - 1].val = A[i][j];
trimat[trimat.length - 1].i = i;
trimat[trimat.length - 1].j = j;
++k;
}
}
}
trimat[0].val = k - 1;//存储非零元素个数
trimat[0].i = m;//存储原矩阵行数
trimat[0].j = n;//存储原矩阵列数
}
}
2)十字链表表示法
package matrix.crosslist;
/**
* @author 芜情 十字链表存储矩阵
*/
public class Matrix {
// 元素节点
@SuppressWarnings("unused")
private class Node {
int row;// 行号
int col;// 列号
int val;// 元素值
Node right;// 右指针
Node down;// 下指针
public Node(int m, int n, int v) {
row = m;
col = n;
val = v;
}
public Node() {
row = -1;
col = -1;
}
}
// 十字链表
@SuppressWarnings("unused")
private class CrossList {
int rownum;// 行数
int colnum;// 列数
int valnum;// 非零元素个数
Node[] chead;// 列头结点(上)
Node[] rhead;// 行头结点(左)
//存储行数、列数,初始化头结点数组
public CrossList(int m, int n) {
rownum = m;
colnum = n;
chead = new Node[n];
for (int i = 0; i < n; i++) {
chead[i] = new Node();
}
rhead = new Node[m];
for (int i = 0; i < m; i++) {
rhead[i] = new Node();
}
}
}
private CrossList list;// 矩阵的属性:十字链表存储
// 创建矩阵,并用十字链表存储,默认传入的是矩阵形式,不做格式判断了
public Matrix(int[][] A) {
int m = A.length;
int n = A[0].length;
int k = 0;
list = new CrossList(m, n);
Node[] temp_c = new Node[n];//构造竖向链表的辅助指针数组
for (int x = 0; x < n; x++) {
temp_c[x] = list.chead[x];//把chead数组赋值给列头结点的辅助指针数组
}
for (int i = 0; i < m; i++) {
Node temp_r = list.rhead[i];//构造横向链表辅助指针
for (int j = 0; j < n; j++) {
//尾插法
if (A[i][j] != 0) {
Node node = new Node(i, j, A[i][j]);
temp_r.right = node;
temp_r = node;
temp_c[j].down = node;
temp_c[j] = node;
++k;
}
}
}
list.valnum = k;//赋值非零元素个数
}
}