Tìm chu trình DFS

 avatar
user_1164828
c_cpp
a year ago
1.8 kB
4
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 stack[MAX];
int top = -1;
int num_vertices;

bool dfs_cycle_detection(int start) {
    // Đặ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;
    }

    // Đẩy đỉnh bắt đầu vào ngăn xếp
    stack[++top] = start;
    visited[start] = true;

    while (top != -1) {
        int current = stack[top--];

        for (int i = 0; i < num_vertices; ++i) {
            if (graph[current][i] == 1) {
                if (!visited[i]) {
                    visited[i] = true;
                    parent[i] = current;
                    stack[++top] = i;
                } else if (parent[current] != 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 = dfs_cycle_detection(0);

    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