zoukankan      html  css  js  c++  java
  • 图的深度优先搜索(非递归)

    样例输入

    4
    0 1 0 1
    1 0 0 0
    0 0 0 1
    1 0 1 0

    样例输出

    0 1 3 2
     1 #include <stdio.h>
     2 #include <memory.h>
     3 #define COUNT 55
     4 typedef struct {
     5     int arc[COUNT][COUNT];
     6     int verNum;
     7 }Graph;
     8 void create(Graph *G){
     9     scanf("%d",&G->verNum);
    10     for(int i = 0; i < G->verNum; i++)
    11         for(int j = 0; j < G->verNum; j++)
    12             scanf("%d",&G->arc[i][j]);
    13 }
    14 void DFS(Graph G){//从结点0开始访问
    15     int degree[COUNT];
    16     int hang,lie;
    17     int stack[COUNT],top = 0;
    18     int arc;
    19     stack[top++] = 0;
    20     memset(degree,1,COUNT * sizeof(int));
    21     while(top > 0){
    22         arc = stack[top - 1];
    23         if(degree[arc]){
    24             printf("%d ",arc);
    25             degree[arc] = 0;
    26         }
    27         for(lie = 0; lie < G.verNum; lie++){
    28             if(G.arc[arc][lie] && degree[lie]){
    29                 stack[top++] = lie;
    30                 break;
    31             }
    32         }
    33         if(lie == G.verNum)
    34             arc = stack[--top];
    35     }
    36 }
    37 int main(){
    38     Graph G;
    39     create(&G);
    40     DFS(G);
    41     printf("
    ");
    42     return 0;
    43 }
     
  • 相关阅读:
    在不给spring管理的类中获取类
    poi操作excel
    闭包
    输入url的过程发生了什么?
    跨域
    函数节流-防抖函数
    预解析-案例
    移动端适配方案
    实现元素水平居中和垂直居中的几种方法
    css小知识点
  • 原文地址:https://www.cnblogs.com/yfs123456/p/5510440.html
Copyright © 2011-2022 走看看