#include <iostream>
#include <fstream>
#include <iomanip>
#include <queue>
using namespace std;
int visited[100];
int nSoMienLienThong;
struct GRAPH {
int sodinh;
int a[100][100];
};
void readGRAPH(string fn, GRAPH& g) {
ifstream f;
f.open(fn);
if (f.is_open()) {
f >> g.sodinh;
for (int i = 0; i < g.sodinh; i++)
for (int j = 0; j < g.sodinh; j++)
f >> g.a[i][j];
f.close();
}
else {
cout << "khong mo duoc file!!";
}
}
void printGRAPH(GRAPH g) {
cout << "so dinh cua do thi la:" << g.sodinh << endl;
for (int i = 0; i < g.sodinh; i++) {
for (int j = 0; j < g.sodinh; j++)
cout << setw(4) << g.a[i][j];
cout << endl;
}
}
/*void visit(GRAPH g, int i, int nLabel) {
//gan nhan nLabel chi dinh i
visited[i] = nLabel;
//goi Visit voi cac dinh j chua duoc vieng tham va chua noi voi i
for (int j = 0; j < g.sodinh; j++)
if ((visited[j] == 0) && (g.a[i][j] != 0))
visit(g, j, nLabel);
}*/void visit(GRAPH g, int i, int nLabel) {
visited[i] = nLabel;
queue <int> q;
q.push(i);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int j = 0; j < g.sodinh; j++) {
if (visited[j] == 0 && g.a[u][j] != 0) {
visited[j] = nLabel;
q.push(j);
}
}
}
}
void XetLienThong(GRAPH& g) {
for (int i = 0; i < g.sodinh; ++i)
visited[i] = 0;
nSoMienLienThong = 0;
for (int i=0;i<g.sodinh;++i)
if (visited[i] == 0) {
nSoMienLienThong++;
visit(g, i, nSoMienLienThong);
}
}
void InThanhPhanLienThong(GRAPH g) {
cout << "So Mien Lien Thong:" << nSoMienLienThong << endl;
for (int i = 1; i <= nSoMienLienThong; i++) {
cout << "Mien Lien Thong Thu" << " " << i << endl;
for (int j = 0; j < g.sodinh; j++)
if (visited[j] == i)
cout << setw(4) << j;
cout << endl;
}
}
int main() {
string fn;
GRAPH a;
readGRAPH("text.txt", a);
printGRAPH(a);
XetLienThong(a);
if (nSoMienLienThong == 0) {
cout << "LIEN THONG" << endl;
}
else {
cout << "KHONG LIEN THONG" << endl;
}
InThanhPhanLienThong(a);
}