DFS非递归算法

#include <stdio.h>
#include <stdlib.h>

#define MAX_VERTICES 100

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

typedef struct Graph {
    int numVertices;
    Node* adjacencyList[MAX_VERTICES];
    int visited[MAX_VERTICES];
} Graph;

typedef struct Stack {
    int data[MAX_VERTICES];
    int top;
} Stack;

void initializeGraph(Graph* graph, int numVertices) {
    graph->numVertices = numVertices;
    for (int i = 0; i < numVertices; i++) {
        graph->adjacencyList[i] = NULL;
        graph->visited[i] = 0;
    }
}

void addEdge(Graph* graph, int src, int dest) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = dest;
    newNode->next = graph->adjacencyList[src];
    graph->adjacencyList[src] = newNode;
}

void dfsNonRecursive(Graph* graph, int startVertex) {
    Stack stack;
    stack.top = -1;

    stack.data[++stack.top] = startVertex;
    graph->visited[startVertex] = 1;

    while (stack.top >= 0) {
        int currentVertex = stack.data[stack.top--];
        printf("Visited: %d\n", currentVertex);

        Node* temp = graph->adjacencyList[currentVertex];
        while (temp != NULL) {
            int adjVertex = temp->data;
            if (graph->visited[adjVertex] == 0) {
                stack.data[++stack.top] = adjVertex;
                graph->visited[adjVertex] = 1;
            }
            temp = temp->next;
        }
    }
}

int main() {
    Graph graph;
    int numVertices = 6;
    initializeGraph(&graph, numVertices);

    addEdge(&graph, 0, 1);
    addEdge(&graph, 0, 2);
    addEdge(&graph, 1, 3);
    addEdge(&graph, 1, 4);
    addEdge(&graph, 2, 5);
    addEdge(&graph, 3, 5);
    dfsNonRecursive(&graph, 0);

    return 0;
}

编译执行

cc a.c
./a.out

多谢评论区的朋友指出错误.

记于2021年12月3日:
再次感谢黑河岛、'Best Wishes、yinwu_、萧瑟1

  • 11
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 18
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值