#include<iostream>
#define N 4
#define MATRIX_SIZE 4
using namespace std;
void show(int a[MATRIX_SIZE][MATRIX_SIZE])
{
for (int i = 0; i < MATRIX_SIZE; i++)
{
for (int j = 0; j < MATRIX_SIZE; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
}
void multi(int a1[MATRIX_SIZE][MATRIX_SIZE], int tempa[MATRIX_SIZE][MATRIX_SIZE],int an[MATRIX_SIZE][MATRIX_SIZE])
{
for (int i = 0; i < MATRIX_SIZE; i++)
{
for (int j = 0; j < MATRIX_SIZE; j++)
{
an[i][j] = 0; //为确保an每次记录的都是最新的Al,每次an要清零
}
}
int temp = 0;
for (int i = 0; i < MATRIX_SIZE; i++)
{
for (int k = 0; k < MATRIX_SIZE; k++)
{
temp = tempa[i][k];
for (int j = 0; j < MATRIX_SIZE; j++)
{
an[i][j] += temp * a1[k][j]; //速度更快,矩阵乘法,第一遍求出a2
}
}
}
}
int main()
{
int a1[MATRIX_SIZE][MATRIX_SIZE] = { 0 }, tempa[MATRIX_SIZE][MATRIX_SIZE] = { 0 },
an[MATRIX_SIZE][MATRIX_SIZE] = { 0 }, flag[MATRIX_SIZE][MATRIX_SIZE] = { 0 }; //tempa用来备份更高阶
cout << "请输入邻接矩阵:" << endl;
for (int i = 0; i < MATRIX_SIZE; i++)
{
for (int j = 0; j < MATRIX_SIZE; j++)
{
cin >> a1[i][j];
tempa[i][j] = a1[i][j]; //记录第一遍的a1
flag[i][j] = a1[i][j]; //flag用来记录是否有路径可抵达
if (i == j)
flag[i][j] = 1; //可达矩阵可达自己,对角线为1
}
}
for (int n = 1; n < N; n++) //从1开始因为最初就是邻接矩阵
{
multi(a1, tempa, an);
for (int i = 0; i < MATRIX_SIZE; i++)
{
for (int j = 0; j < MATRIX_SIZE; j++)
{
tempa[i][j] = an[i][j]; //储存每次升阶的矩阵
flag[i][j] += an[i][j]; //记录每个路径的结果,不为0就可
}
}
}
int sum = 0; //记录长度为N的通路数
for (int i = 0; i < MATRIX_SIZE; i++)
{
for (int j = 0; j < MATRIX_SIZE; j++)
{
if (flag[i][j] != 0)
flag[i][j] = 1;
sum += tempa[i][j];
}
}
cout << "A" << N << "为:" << endl;
show(tempa);
cout << "长度为" << N << "的通路数为:" << sum << endl;
for (int i = 0; i < MATRIX_SIZE; i++)
for (int j = 0; j < MATRIX_SIZE; j++)
if (flag[i][j]!=0)
flag[i][j] = 1;
cout << "可达矩阵为:" << endl;
show(flag);
return 0;
}
【离散数学】编程实现矩阵乘法和可达矩阵
最新推荐文章于 2024-03-22 18:32:54 发布