Tìm chu trình và in ra DFS - Đệ quy
user_1164828
plain_text
a year ago
2.6 kB
12
Indexable
#include <iostream>
using namespace std;
// Khai báo các biến toàn cục
const int MAX = 100;
int graph[MAX][MAX];
bool visited[MAX];
int parent[MAX];
bool in_cycle[MAX];
int cycle[MAX];
int num_vertices;
// Hàm tìm chu trình bằng DFS đệ quy
bool dfs_cycle_detection(int current) {
visited[current] = true;
for (int i = 0; i < num_vertices; ++i) {
if (graph[current][i] == 1) {
if (!visited[i]) {
parent[i] = current;
if (dfs_cycle_detection(i)) {
return true;
}
} else if (parent[current] != i) {
// Phát hiện chu trình, bắt đầu từ i đến current
int cycle_index = 0;
int temp = current;
while (temp != i) {
cycle[cycle_index++] = temp;
temp = parent[temp];
}
cycle[cycle_index++] = i;
//cycle[cycle_index++] = current;
// In ra chu trình
cout << "Chu trinh: ";
for (int j = cycle_index - 1; j >= 0; --j) {
cout << cycle[j] << " ";
}
cout << endl;
return true;
}
}
}
return false;
}
bool has_cycle() {
// Đặt tất cả các đỉnh là chưa được thăm
for (int i = 0; i < num_vertices; ++i) {
visited[i] = false;
parent[i] = -1;
in_cycle[i] = false;
}
// Kiểm tra từng đỉnh chưa được thăm để phát hiện chu trình
for (int i = 0; i < num_vertices; ++i) {
if (!visited[i]) {
if (dfs_cycle_detection(i)) {
return true;
}
}
}
return false;
}
int main() {
// Số lượng đỉnh trong đồ thị
num_vertices = 5;
// Ma trận kề của đồ thị
int temp_graph[5][5] = {
{0, 0, 0, 1, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 1},
{0, 1, 0, 0, 0},
{1, 0, 0, 0, 0},
};
// Sao chép dữ liệu từ temp_graph vào graph toàn cục
for (int i = 0; i < num_vertices; ++i) {
for (int j = 0; j < num_vertices; ++j) {
graph[i][j] = temp_graph[i][j];
}
}
if (has_cycle()) {
cout << "Do thi co chu trinh." << endl;
} else {
cout << "Do thi khong co chu trinh." << endl;
}
return 0;
}
Editor is loading...
Leave a Comment