c语言深度优先搜索。代码
答案:1 悬赏:80 手机版
解决时间 2021-12-03 08:46
- 提问者网友:练爱
- 2021-12-02 17:11
c语言深度优先搜索。代码
最佳答案
- 五星知识达人网友:神的生死簿
- 2021-12-02 18:12
#include
#include
struct node
{
int vertex;
struct node *nextnode;
};
typedef struct node *graph;
struct node head[9];
int visited[9];
void creategraph(int node[20][2],int num)
{
graph newnode;
graph ptr;
int from;
int to;
int i;
for ( i = 0; i < num; i++ )
{
from = node[i][0];
to = node[i][1];
newnode = ( graph ) malloc(sizeof(struct node));
newnode->vertex = to;
newnode->nextnode = NULL;
ptr = &(head[from]);
while ( ptr->nextnode != NULL )
ptr = ptr->nextnode;
ptr->nextnode = newnode;
}
}
void dfs(int current)
{
graph ptr;
visited[current] = 1;
printf("vertex[%d]
",current);
ptr = head[current].nextnode;
while ( ptr != NULL )
{
if ( visited[ptr->vertex] == 0 )
dfs(ptr->vertex);
ptr = ptr->nextnode;
}
}
int main()
{
graph ptr;
int node[20][2] = { {1, 2}, {2, 1},
{1, 3}, {3, 1},
{1, 4}, {4, 1},
{2, 5}, {5, 2},
{2, 6}, {6, 2},
{3, 7}, {7, 3},
{4, 7}, {4, 4},
{5, 8}, {8, 5},
{6, 7}, {7, 6},
{7, 8}, {8, 7} };
int i;
//clrscr();
for ( i = 1; i <= 8; i++ )
{
head[i].vertex = i;
head[i].nextnode = NULL;
visited[i] = 0;
}
creategraph(node,20);
printf("Content of the gragh's ADlist is:
");
for ( i = 1; i <= 8; i++ )
{
printf("vertex%d ->",head[i].vertex);
ptr = head[i].nextnode;
while ( ptr != NULL )
{
printf(" %d ",ptr->vertex);
ptr = ptr->nextnode;
}
printf("
");
}
printf("
The end of the dfs are:
");
dfs(1);
printf("
");
puts(" Press any key to quit...");
// getch();
}
#include
struct node
{
int vertex;
struct node *nextnode;
};
typedef struct node *graph;
struct node head[9];
int visited[9];
void creategraph(int node[20][2],int num)
{
graph newnode;
graph ptr;
int from;
int to;
int i;
for ( i = 0; i < num; i++ )
{
from = node[i][0];
to = node[i][1];
newnode = ( graph ) malloc(sizeof(struct node));
newnode->vertex = to;
newnode->nextnode = NULL;
ptr = &(head[from]);
while ( ptr->nextnode != NULL )
ptr = ptr->nextnode;
ptr->nextnode = newnode;
}
}
void dfs(int current)
{
graph ptr;
visited[current] = 1;
printf("vertex[%d]
",current);
ptr = head[current].nextnode;
while ( ptr != NULL )
{
if ( visited[ptr->vertex] == 0 )
dfs(ptr->vertex);
ptr = ptr->nextnode;
}
}
int main()
{
graph ptr;
int node[20][2] = { {1, 2}, {2, 1},
{1, 3}, {3, 1},
{1, 4}, {4, 1},
{2, 5}, {5, 2},
{2, 6}, {6, 2},
{3, 7}, {7, 3},
{4, 7}, {4, 4},
{5, 8}, {8, 5},
{6, 7}, {7, 6},
{7, 8}, {8, 7} };
int i;
//clrscr();
for ( i = 1; i <= 8; i++ )
{
head[i].vertex = i;
head[i].nextnode = NULL;
visited[i] = 0;
}
creategraph(node,20);
printf("Content of the gragh's ADlist is:
");
for ( i = 1; i <= 8; i++ )
{
printf("vertex%d ->",head[i].vertex);
ptr = head[i].nextnode;
while ( ptr != NULL )
{
printf(" %d ",ptr->vertex);
ptr = ptr->nextnode;
}
printf("
");
}
printf("
The end of the dfs are:
");
dfs(1);
printf("
");
puts(" Press any key to quit...");
// getch();
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯