#include <iostream>
#include <vector>
#include <stack>
#include <algorithm> // sort
using namespace std;

int main() {
    int n, start;
    cin >> n >> start;

    vector<vector<int>> graph(n);

    // 각 노드의 인접 노드 입력
    for (int i = 0; i < n; i++) {
        int x;
        while (cin >> x) {
            graph[i].push_back(x);
            if (cin.peek() == '\n') break;
        }
        // 인접 노드 정렬 (오름차순)
        sort(graph[i].begin(), graph[i].end());
    }

    vector<bool> visited(n, false);
    stack<int> st;
    st.push(start);

    while (!st.empty()) {
        int cur = st.top();
        st.pop();

        if (visited[cur]) continue;
        visited[cur] = true;
        cout << cur << " ";

        // 큰 번호부터 스택에 넣기
        for (int i = (int)graph[cur].size() - 1; i >= 0; i--) {
            int next = graph[cur][i];
            if (!visited[next]) st.push(next);
        }
    }

    cout << endl;
    return 0;
}

Embed on website

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