#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    int N, M, V;
    cin >> N >> M >> V;

    vector<int> graph[1001];
    bool visited[1001];

    // 간선 입력
    for (int i = 0; i < M; i++)
    {
        int a, b;
        cin >> a >> b;

        graph[a].push_back(b);
        graph[b].push_back(a);
    }

    // 작은 번호부터 방문하도록 정렬
    for (int i = 1; i <= N; i++)
    {
        sort(graph[i].begin(), graph[i].end());
    }

    // 방문 배열 초기화
    for (int i = 1; i <= N; i++)
    {
        visited[i] = false;
    }

    // DFS (stack 사용)
    vector<int> stack;
    stack.push_back(V);

    while (stack.empty() == false)
    {
        int v = stack.back();
        stack.pop_back();

        if (visited[v] == true)
        {
            continue;
        }

        visited[v] = true;
        cout << v << " ";

        // 역순으로 넣기 (스택 특성 때문에)
        for (int i = graph[v].size() - 1; i >= 0; i--)
        {
            int next = graph[v][i];

            if (visited[next] == false)
            {
                stack.push_back(next);
            }
        }
    }

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: