Tìm chu trình BFS
user_1164828
c_cpp
a year ago
1.9 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]; int queue[MAX]; bool visited[MAX]; int parent[MAX]; int front = 0; int rear = 0; int num_vertices; bool bfs_cycle_detection(int start) { // Đặt các giá trị ban đầu front = 0; rear = 0; // Đặ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; } // Đưa đỉnh bắt đầu vào hàng đợi queue[rear++] = start; visited[start] = true; while (front != rear) { int current = queue[front++]; for (int i = 0; i < num_vertices; ++i) { if (graph[current][i] == 1) { if (!visited[i]) { visited[i] = true; parent[i] = current; queue[rear++] = 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 = bfs_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