/*Warshall算法求给定关系的传递闭包*/
#include<iostream>
#include<vector>
using namespace std;
void Warshall(vector<vector<int>>M1, vector<vector<int>>& M2);
void SumArray(vector<int>& a, vector<int>& b);
void MakeMartix(vector<vector<int>>& M);
void ShowMartix(vector<vector<int>>M);
void Warshall(vector<vector<int>>M1, vector<vector<int>>& M2) {//M1为由用户输入的关系矩阵,M2为存储输出的传递关系的矩阵
for (int j = 0; j < M1.size(); j++) {//j为列
for (int i = 0; i < M1[j].size(); i++) {//i为行
if (M1[i][j] == 1)//第j列第i行元素<i,j>=1,则将第j行加到第i行上
SumArray(M2[i], M2[j]);//M2=M1+M2
}
}
for (int i = 0; i < M2.size(); i++) {
for (int j = 0; j < M2[i].size(); j++) {
if (M2[i][j] > 1)
M2[i][j] = 1;
}
}
}
void SumArray(vector<int>& a, vector<int>& b) {//a=a+b
for (int i = 0; i < a.size(); i++) {
a[i] += b[i];
}
}
void MakeMartix(vector<vector<int>>& M) {
for (int i = 0; i < M.size(); i++) {
cout << "输入第" << i + 1 << "行矩阵元素:";
for (int j = 0; j < M[i].size(); j++) {
cin >> M[i][j];
}
}
}
void ShowMartix(vector<vector<int>>M) {
for (int i = 0; i < M.size(); i++) {
for (int j = 0; j < M[i].size(); j++) {
cout << M[i][j] << " ";
}
cout << endl;
}
}
int main() {
int N = 4;//设定集合包含的元素个数
vector<vector<int>>M1(N, vector<int>(N));
MakeMartix(M1);
vector<vector<int>>M2(M1);
cout << "原始关系矩阵为:" << endl;
ShowMartix(M1);
Warshall(M1, M2);
cout << "由Warshall求得的传递闭包为:" << endl;
ShowMartix(M2);
}