写一个dfs C++程序
时间: 2023-03-19 19:23:34 浏览: 49
我可以给你一个简单的深度优先搜索(DFS)C程序示例:#include <stdio.h> #define MAX_VERTICES 100 int graph[MAX_VERTICES][MAX_VERTICES];
int visited[MAX_VERTICES];
int n; // number of vertices // Function to traverse the graph in depth-first manner
void dfs(int v)
{
// Mark the current node as visited
visited[v] = 1;
// Print the current node
printf("%d ", v);
// Recursively traverse for all the vertices
// adjacent to the current vertex
for (int i = 0; i < n; i++) {
if (graph[v][i] == 1 && visited[i] == 0) {
dfs(i);
}
}
} // Driver code
int main()
{
// Input the number of vertices
printf("Enter the number of vertices: ");
scanf("%d", &n);
// Input the adjacency matrix
printf("Enter the adjacency matrix: \n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}
// Initialize visited array
for (int i = 0; i < n; i++) {
visited[i] = 0;
}
// Do DFS traversal from the first vertex
dfs(0);
return 0;
}