카테고리 없음

Graph DFS, BFS

fw93 2018. 4. 15. 11:03
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
 
using namespace std;
 
void addedge(vector<vector<int>>& graph, int u, int v) {
    if (u >= graph.size() || v >= graph.size()) return;
    graph[u].push_back(v);
    graph[v].push_back(u);
}
 
void print(vector<vector<int>> & graph) {
    for (int i = 0; i < graph.size(); i++) {
        cout << "node " << i << "'s adjacents ";
        for (int j = 0; j < graph[i].size(); j++) {
            cout << graph[i][j] << " ";
        }
        cout << endl;
    }
}
 
void DFSUtil(int u, vector<vector<int>> & graph, vector<bool> & visited) {
    visited[u] = true;
    cout << u << " ";
    for (int i = 0; i < graph[u].size(); i++) {
        if (visited[graph[u][i]] == false) {
            DFSUtil(graph[u][i], graph, visited);
        }
    }
}
 
void DFS(vector<vector<int>> & graph) {
    vector<bool> visited(graph.size(), false);
    for (int i = 0; i < graph.size(); i++) {
        if (visited[i] == false) {
            DFSUtil(i,graph,visited);
        }
    }
}
 
void DFSiter(vector<vector<int>> & graph) {
    vector<bool> visited(graph.size(), false);
    stack<int> buffer;
    buffer.push(0);
    while (buffer.size() != 0) {
        int curr = buffer.top();
        buffer.pop();
        if (visited[curr] != true) {
            visited[curr] = true;
            cout << curr << " ";
        }
        for (int i = graph[curr].size()-1; i >=0; i--) {
            if (visited[graph[curr][i]] == false) buffer.push(graph[curr][i]);
        }
    }
    return;
}
 
void BFS(vector<vector<int>> & graph) {
    vector<bool> visited(graph.size(), false);
    queue<int> buffer;
    buffer.push(0);
    while (buffer.size() != 0) {
        int curr = buffer.front();;
        buffer.pop();
        if (visited[curr] != true) {
            visited[curr] = true;
            cout << curr << " ";
        }
        for (int i = graph[curr].size()-1; i >=0; i--) {
            if (visited[graph[curr][i]] == false) buffer.push(graph[curr][i]);
        }
    }
}
 
 
 
int main() {
    vector<vector<int>> graph(10, vector<int>());
    addedge(graph, 1, 2);
    addedge(graph, 2, 4);
    addedge(graph, 3, 1);
    addedge(graph, 5, 2);
    addedge(graph, 7, 2);
    addedge(graph, 7, 3);
    addedge(graph, 8, 4);
    addedge(graph, 6, 3);
    addedge(graph, 9, 1);
    addedge(graph, 0, 6);
    DFS(graph);
    cout << endl;
    DFSiter(graph);
    cout << endl;
    BFS(graph);
    while(1){}
    return 0;
}
cs