99.png

    1. /*
    2. 写出深度优先遍历的非递归算法(图用邻接表给出)
    3. 分析:
    4. 之前我们也做过将一个递归算法利用栈用非递归的方式算出来,这里同理,我们利用栈来进行深度优先遍历
    5. 算法过程大致如下:从第一个顶点开始进行深度优先遍历,同时置访问位为true,然后将该顶点入栈,
    6. 采用while循环,依次取出栈顶元素,并判断该顶点元素是否已访问,未访问则访问,
    7. 已访问则查看它的firstEdge,当firstEdge也被访问了,查看next,如此循环。
    8. */
    9. #include <stdio.h>
    10. #include <stdlib.h>
    11. #define _CRT_SECURE_NO_WARNINGS
    12. #define MAXSIZE 100
    13. struct Stack {//栈结构
    14. int *arr;
    15. int len;
    16. int top;
    17. };
    18. typedef struct EdgeNode {//边表结点
    19. int index;//该边所指向的顶点的位置
    20. int weight;//权值
    21. EdgeNode *next;//下一个邻接边
    22. }EdgeNode;
    23. typedef struct VertexNode {//顶点表节点
    24. char info;//顶点信息
    25. EdgeNode *firstEdge;//指向第一条依附该顶点的边的指针
    26. }VertexNode, Adjlist[MAXSIZE];
    27. typedef struct {
    28. Adjlist adjlist;//顶点数组
    29. int numE, numV;//边数、顶点数
    30. }ALGraph;
    31. void DFSUseStack(ALGraph *G, Stack *s) {
    32. bool push(Stack *, int);
    33. bool pop(Stack *);
    34. int top(Stack *);
    35. bool empty(Stack *);
    36. int *visited = (int *)malloc(sizeof(int)*G->numV);//设置标记数组
    37. for (int i = 0; i < G->numV; i++) {
    38. visited[i] = 0;
    39. }
    40. for (int i = 0; i < G->numV; i++) {
    41. if (visited[i])
    42. continue;
    43. int v;
    44. printf("%c ", G->adjlist[i].info);
    45. visited[i] = 1;
    46. push(s, i);//入栈
    47. EdgeNode *p;
    48. while (!empty(s)) {//栈内不空
    49. v = top(s);
    50. pop(s);
    51. p = G->adjlist[v].firstEdge;
    52. while (p) {
    53. if (!visited[p->index]) {
    54. printf("%c ", G->adjlist[p->index].info);
    55. visited[p->index] = 1;
    56. push(s, p->index);
    57. p = G->adjlist[p->index].firstEdge;//顺腾摸瓜
    58. }
    59. else {
    60. p = p->next;//摸到底了,平级顶点继续找
    61. }
    62. }
    63. if (p == NULL)
    64. pop(s);
    65. //printf("%c ", G->adjlist[v].info);
    66. //for (p = G->adjlist[v].firstEdge; p; p = p->next) {
    67. // if (!visited[p->index]) {
    68. // push(s, p->index);
    69. // visited[p->index] = 1;
    70. // //p = G->adjlist[p->index].firstEdge;//顺腾摸瓜
    71. // }
    72. //}
    73. }
    74. }
    75. }
    76. int main() {
    77. ALGraph G;
    78. void createGraphInFile(ALGraph *);
    79. void dispGraph(ALGraph *);
    80. createGraphInFile(&G);//创建图
    81. dispGraph(&G);
    82. Stack *s = (Stack *)malloc(sizeof(Stack *));
    83. Stack *createStack(int);
    84. s = createStack(G.numV);
    85. DFSUseStack(&G, s);
    86. return 0;
    87. }