用c语言写一段关于图论、逻辑的代码
时间: 2023-12-03 17:42:40 浏览: 24
以下是一个简单的使用图论和逻辑运算的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTICES 100
#define MAX_EDGES 100
typedef struct {
int start;
int end;
} Edge;
typedef struct {
int vertices[MAX_VERTICES];
Edge edges[MAX_EDGES];
int num_vertices;
int num_edges;
} Graph;
void add_vertex(Graph* graph, int vertex) {
if (graph->num_vertices >= MAX_VERTICES) {
printf("Graph is full!");
return;
}
graph->vertices[graph->num_vertices++] = vertex;
}
void add_edge(Graph* graph, int start, int end) {
if (graph->num_edges >= MAX_EDGES) {
printf("Graph is full!");
return;
}
graph->edges[graph->num_edges].start = start;
graph->edges[graph->num_edges++].end = end;
}
bool is_connected(Graph* graph, int vertex1, int vertex2) {
for (int i = 0; i < graph->num_edges; i++) {
if ((graph->edges[i].start == vertex1 && graph->edges[i].end == vertex2) ||
(graph->edges[i].start == vertex2 && graph->edges[i].end == vertex1)) {
return true;
}
}
return false;
}
bool is_path(Graph* graph, int vertex1, int vertex2) {
if (is_connected(graph, vertex1, vertex2)) {
return true;
}
bool visited[MAX_VERTICES] = {false};
visited[vertex1] = true;
for (int i = 0; i < graph->num_vertices; i++) {
if (is_connected(graph, vertex1, i) && !visited[i]) {
visited[i] = true;
if (is_path(graph, i, vertex2)) {
return true;
}
}
}
return false;
}
int main() {
Graph graph = {0};
add_vertex(&graph, 0);
add_vertex(&graph, 1);
add_vertex(&graph, 2);
add_vertex(&graph, 3);
add_edge(&graph, 0, 1);
add_edge(&graph, 1, 2);
add_edge(&graph, 2, 3);
add_edge(&graph, 3, 0);
int vertex1 = 0;
int vertex2 = 2;
if (is_path(&graph, vertex1, vertex2)) {
printf("There is a path from vertex %d to vertex %d.\n", vertex1, vertex2);
} else {
printf("There is no path from vertex %d to vertex %d.\n", vertex1, vertex2);
}
return 0;
}
```
这段代码定义了一个简单的图,并使用深度优先搜索算法来查找两个给定顶点之间是否存在路径。可以通过添加更多的顶点和边来扩展图的规模,并尝试不同的顶点组合来测试算法的正确性。