Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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
Tags more
Archives
Today
Total
관리 메뉴

난 정말 최고야 멋있어

[BOJ] DFS와 BFS 본문

카테고리 없음

[BOJ] DFS와 BFS

n00bh4cker 2020. 1. 8. 20:22
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

class Graph
{
private:
    int start;
    vector<vector<int>> _graph;
    vector<bool> _checked;
public:
    Graph(int size, int start) : start(start-1) 
    {
        _graph.resize(size);
        _checked.resize(size, false);
    }
    void connect(int i, int j)
    {
        _graph[i - 1].emplace_back(j - 1);
        _graph[j - 1].emplace_back(i - 1);
    }

    void dfs(int start)
    {
        _checked[start] = true;
        cout << start + 1 << " ";
        for (auto i = _graph[start].begin(); i < _graph[start].end() ; i++)
        {
            if (_checked[*i] == false)
                dfs(*i);
        }
    }

    void bfs(int start) {
        queue<int> q;

        q.push(start);
        _checked[start] = true;
    loop:
        for (auto i = _graph[start].begin(); i < _graph[start].end(); i++)
        {
            if (_checked[*i] == false)
            {
                q.push(*i);
                _checked[*i] = true;
            }
        }

        cout << q.front() + 1 << " ";
        q.pop();
        if (q.empty())
            return;
        start = q.front();
        goto loop;
    }

    void _sort()
    {
        for (auto& i : _graph)
        {   
            sort(i.begin(), i.end());
        }
    }

    void _clear()
    {
        for (auto i = _checked.begin(); i < _checked.end(); i++)
        {
            *i = false;
        }
        cout << "\n";
    }
};

int main()
{
    vector<vector<int>> dot_dot;
    int dot, line, start;
    cin >> dot;
    cin >> line;
    cin >> start;
    Graph g(dot,start);
    for (int i = 0; i < line; i++)
    {
        int dt1, dt2;
        cin >> dt1;
        cin >> dt2;
        g.connect(dt1, dt2);
    }
    g._sort();
    g.dfs(start-1);
    g._clear();
    g.bfs(start-1);
}

..ㅎ

야매로 짠녀석들이라서 엉성하다..