以邻接矩阵表示法创建有向图,并基于图的深度优先遍历策略设计一算法,判断有向图中是否存在由顶点A到顶点B的路径。
#include <iostream>
#include <stack>
#include <cstring>
struct Graph {
int v_num; // 顶点数
int** adj_matrix; // 邻接矩阵
};
bool has_path(Graph* graph, int A, int B) {
if (A == B) {
return true;
}
// 深度优先遍历
bool visited[graph->v_num];
memset(visited, false, graph->v_num * sizeof(bool));
std::stack<int> s;
s.push(A);
visited[A] = true;
while (!s.empty()) {
int curr = s.top();
s.pop();
for (int i = 0; i < graph->v_num; i++) {
if (graph->adj_matrix[curr][i] && !visited[i]) {
if (i == B) {
return true;
}
s.push(i);
visited[i] = true;
}
}
}
return false;
}
Graph* create_graph() {
Graph* graph = new Graph;
graph->v_num = 5;
graph->adj_matrix = new int*[graph->v_num];
for (int i = 0; i < graph->v_num; i++) {
graph->adj_matrix[i] = new int[graph->v_num];
memset(graph->adj_matrix[i], 0, graph->v_num * sizeof(int));
}
graph->adj_matrix[0][1] = 1;
graph->adj_matrix[0][2] = 1;
graph->adj_matrix[1][3] = 1;
graph->adj_matrix[2][3] = 1;
graph->adj_matrix[3][4] = 1;
return graph;
}
int main() {
Graph* graph = create_graph();
int A = 0, B = 4;
if (has_path(graph, A, B)) {
std::cout << "There is a path from vertex " << A << " to vertex " << B << "." << std::endl;
} else {
std::cout << "There is no path from vertex " << A << " to vertex " << B << "." << std::endl;
}
return 0;
}