fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <iomanip>
  4. #include <queue>
  5. using namespace std;
  6. int visited[100];
  7. int nSoMienLienThong;
  8. struct GRAPH {
  9. int sodinh;
  10. int a[100][100];
  11.  
  12. };
  13. void readGRAPH(string fn, GRAPH& g) {
  14. ifstream f;
  15. f.open(fn);
  16. if (f.is_open()) {
  17. f >> g.sodinh;
  18. for (int i = 0; i < g.sodinh; i++)
  19. for (int j = 0; j < g.sodinh; j++)
  20. f >> g.a[i][j];
  21. f.close();
  22. }
  23. else {
  24. cout << "khong mo duoc file!!";
  25. }
  26. }
  27. void printGRAPH(GRAPH g) {
  28. cout << "so dinh cua do thi la:" << g.sodinh << endl;
  29. for (int i = 0; i < g.sodinh; i++) {
  30. for (int j = 0; j < g.sodinh; j++)
  31. cout << setw(4) << g.a[i][j];
  32. cout << endl;
  33. }
  34. }
  35. /*void visit(GRAPH g, int i, int nLabel) {
  36. //gan nhan nLabel chi dinh i
  37. visited[i] = nLabel;
  38. //goi Visit voi cac dinh j chua duoc vieng tham va chua noi voi i
  39. for (int j = 0; j < g.sodinh; j++)
  40. if ((visited[j] == 0) && (g.a[i][j] != 0))
  41. visit(g, j, nLabel);
  42. }*/void visit(GRAPH g, int i, int nLabel) {
  43. visited[i] = nLabel;
  44. queue <int> q;
  45. q.push(i);
  46. while (!q.empty()) {
  47. int u = q.front();
  48. q.pop();
  49. for (int j = 0; j < g.sodinh; j++) {
  50. if (visited[j] == 0 && g.a[u][j] != 0) {
  51. visited[j] = nLabel;
  52. q.push(j);
  53. }
  54. }
  55. }
  56. }
  57. void XetLienThong(GRAPH& g) {
  58. for (int i = 0; i < g.sodinh; ++i)
  59. visited[i] = 0;
  60. nSoMienLienThong = 0;
  61. for (int i=0;i<g.sodinh;++i)
  62. if (visited[i] == 0) {
  63. nSoMienLienThong++;
  64. visit(g, i, nSoMienLienThong);
  65. }
  66. }
  67. void InThanhPhanLienThong(GRAPH g) {
  68. cout << "So Mien Lien Thong:" << nSoMienLienThong << endl;
  69. for (int i = 1; i <= nSoMienLienThong; i++) {
  70. cout << "Mien Lien Thong Thu" << " " << i << endl;
  71. for (int j = 0; j < g.sodinh; j++)
  72. if (visited[j] == i)
  73. cout << setw(4) << j;
  74. cout << endl;
  75. }
  76. }
  77. int main() {
  78.  
  79. string fn;
  80. GRAPH a;
  81. readGRAPH("text.txt", a);
  82. printGRAPH(a);
  83. XetLienThong(a);
  84. if (nSoMienLienThong == 0) {
  85. cout << "LIEN THONG" << endl;
  86. }
  87. else {
  88. cout << "KHONG LIEN THONG" << endl;
  89. }
  90. InThanhPhanLienThong(a);
  91.  
  92. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
khong mo duoc file!!so dinh cua do thi la:0
LIEN THONG
So Mien Lien Thong:0