我试图从邻接矩阵中创建有向DFS遍历路径。基本上打印出节点中的路径,但由于某种原因输出总是很糟糕。尽管代码看起来很合理,但它实际上并没有遵循路径。
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
void DFS(int i, int graph[][MAX], int n, int visited[MAX] );
void visit_all(int graph[][MAX], int n);
void read_matrix(int graph [][MAX], int n);
int main() {
int graph[MAX][MAX];
int n;
printf("Input matrix dimension: ");
scanf("%d", &n);
if (n>MAX) {
fprintf(stderr, "Too large\n");
exit(1);
}
read_matrix(graph, n);
visit_all(graph, n);
return 0;
}
void DFS(int v, int graph[][MAX], int n, int visited[MAX]) {
int w;
printf("%d ", v);
visited[v] = 1;
for(w=0;w<n;w++)
if (visited[w] == 0 && graph[v][w] == 1)
DFS(w, graph, n, visited);
}
void visit_all(int graph[][MAX], int n) {
int v, visited[MAX];
for(v=0;v<n;v++)
visited[v] = 0;
for(v=0;v<n;v++)
if (visited[v] == 0)
DFS(v, graph, n, visited);
printf("\n");
}
void read_matrix(int graph [][MAX], int n) {
int i, j;
for(i=0;i<n;i++)
for (j=0;j<n;j++)
graph[i][j] = 0;
printf("\Input elements in format [ij], CTRL+D to end\n");
while(scanf("%d%d", &i, &j) != EOF) {
graph[i][j] = 1;
}
}
答案 0 :(得分:-1)
Input elements in format [ij]
使用%d%d的扫描57不会给你5,7 - 斯塔克