广度优先遍历

Posted 不二小杰

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了广度优先遍历相关的知识,希望对你有一定的参考价值。

额。。一到五个结点就报错。。。

typedef struct
{
    int **table;
    int num;
}Graph; 

typedef struct Queue
{
    int data;
    struct Queue *next;
}Queue;


void createTable(Graph *graph);
void des(Graph *graph); 
void travel(Graph *graph, int first);
void init(Queue *q);
void enQueue(Queue *q, int num);
void deQueue(Queue *q, int *num); 
int emptyQueue(Queue *q); 
 
int main(int argc, char *argv[])
{
    Graph graph;
    
    printf("请输入结点数:");
    scanf("%d", &(graph.num)); 
    createTable(&graph);
    
    travel(&graph, 2); 
    
    
    des(&graph);
    return 0;
}

void travel(Graph *graph, int first)
{
    first -= 1;
    int num = graph->num;
    int **table = graph->table;
    Queue q;
    int i, cur;
    int visit[num];
    
    for(i=0;i<num;i++)
    {
        visit[i] = 0;
     } 
    
    init(&q);
    enQueue(&q, first);
    
    while(!emptyQueue(&q))
    {
        deQueue(&q, &cur);
        printf("%d ", cur+1);
        visit[cur] = 1;
        
        for(i=0; i<num; i++)
        {
            if(table[cur][i] && (!visit[i]))
            {
                visit[i] = 1;
                enQueue(&q, i);
            }
        }
    }
    
}

void init(Queue *q)
{
    q->data = 0;
    q->next = NULL;
}

void enQueue(Queue *q, int num)
{
    Queue *p = q;
    while(p->next)
    {
        p = p->next;
    }
    p->next = (Queue *)malloc(sizeof(Queue));
    p = p->next;
    p->next = NULL;
    p->data = num;    
}

void deQueue(Queue *q, int *num)
{
    Queue *p = q;
    Queue *temp;
    
    if(emptyQueue(q))
    {
        return;
    }
    
    temp = p->next->next;
    *num = p->next->data;
    
    free(p->next);
    p->next = temp;
}

int emptyQueue(Queue *q)
{
    if(q->next)
    {
        return 0;
    }else {
        return 1;
    }
}

void createTable(Graph *graph) 
{
    int num = graph->num; 
    int **table;
    int i, j, temp;
    
    table = (int **)malloc(sizeof(int)*num);
    for(i=0; i<num; i++)
    {
        table[i] = (int *)malloc(sizeof(int)*num);
    }
    
    for(i=0; i<num; i++)
    {
        printf("第 %d 行:", i+1);
        for(j=0;j<num;j++)
        {
            scanf("%d", &temp);
            if(temp ==  )
            {
                j -= 1;
            }else {
                (table)[i][j] = temp;
            }
        }
        getchar();
    }

    graph->table = table; 
    
}

void des(Graph *graph)
{
    int num = graph->num;
    int i, j;
    
    printf("\n");
    for(i=0; i<num; i++)
    {
        for(j=0;j<num;j++)
        {
            printf("%d ", (graph->table)[i][j]);
        }
        printf("\n");
        //free((graph->table)[i]); 
    }
    //free(graph->table);
    graph->num = 0;
}

 

以上是关于广度优先遍历的主要内容,如果未能解决你的问题,请参考以下文章

图的深度优先遍历DFS和广度优先遍历BFS(邻接矩阵存储)超详细完整代码进阶版

介绍下深度优先遍历和广度优先遍历,如何实现?

二叉树遍历(前序中序后序层次深度优先广度优先遍历)

解释 Haskell 广度优先编号代码遍历树

本周学习的代码(数构 深度 广度 优先遍历)

广度优先搜索遍历图