基於鄰接表的深度優先遍歷 (非遞歸)


關鍵:利用棧來保存已經搜索到的頂點,利用top來返回上一個頂點。

描述

 

一個連通圖采用鄰接表作為存儲結構。設計一個算法,實現從頂點v出發的深度優先遍歷的非遞歸過程。

 

輸入

多組數據,每組m+2數據行。第一行有兩個數字n和m,代表有n個頂點和m條邊。頂點編號為1到n。第二行到第m+1行每行有兩個整數h和k,代表邊依附的兩個頂點。第m+2行有一個整數d,代表從d開始遍歷。當n和m都等於0時,輸入結束。

輸出

每組數據輸出一行,為深度優先搜索的遍歷結果。每兩個數字之間用空格隔開。

輸入樣例 1 

3 2
1 2
1 3
1
2 1
1 2
2
0 0

輸出樣例 1

1 2 3
2 1

 

 

#include<iostream>
#define maxn 100
using namespace std;
typedef struct node
{
    int data;
    struct node *next;
} Node;

void DFS(Node *V[], int d)
{
    Node *p;
    int visit[maxn];
    for (int i = 0; i < maxn; i++)
        visit[i] = 0;
    int Stack[maxn];
    int top = 0;
    cout << d;
    Stack[top++] = d;
    visit[d] = 1;
    while (top > 0)
    {
        p = V[Stack[top - 1]];
        int t = -1;
        while (p)
        {
            if (!visit[p->data])
            {
                t = p->data;
            }
            p = p->next;
        }
        if (t == -1)//說明這個點沒有未被訪問的鄰接點
            top--;
        else
        {
            cout << " "<<t;
            Stack[top++] = t;
            visit[t] = 1;
        }
    }
    cout << endl;
}

int main()
{
    int n, m;
    int x, y, d;
    Node *p;
    Node *V[maxn];
    while (1)
    {
        cin >> n >> m;
        if (n == 0 && m == 0)
            break;
        for (int i = 0; i < maxn; i++)
        {
            V[i] = (Node *)malloc(sizeof(Node));
            V[i]->data = 0;
            V[i]->next = NULL;
        }
        while (m--)
        {
            cin >> x >> y;
            V[x]->data = x;
            V[y]->data = y;
            p = (Node *)malloc(sizeof(Node));
            p->data = y;
            p->next = V[x]->next;
            V[x]->next = p;
            p = (Node *)malloc(sizeof(Node));
            p->data = x;
            p->next = V[y]->next;
            V[y]->next = p;
        }
        cin >> d;
        DFS(V, d);
    }
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM