Tìm chu trình DFS - Đệ quy
user_1164828
c_cpp
a year ago
1.9 kB
10
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];
int num_vertices;
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) {
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;
}
// 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, 1, 0, 0, 1},
{1, 0, 1, 0, 0},
{0, 1, 0, 1, 0},
{0, 0, 1, 0, 1},
{1, 0, 0, 1, 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];
}
}
bool has_cycle = has_cycle();
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