11403
1012
    4963
        #include <iostream>
#include <vector>

using namespace std;

int main() {
    int N;
    cin >> N;

    // 1. 인접 리스트 만들기 (연결 정보 저장)
    vector<vector<int>> adj(N);
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            int road;
            cin >> road;
            if (road == 1) {
                adj[i].push_back(j);
            }
        }
    }

    // 2. 모든 정점 i에서 출발해보기
    for (int i = 0; i < N; i++) {
        vector<bool> visited(N, false); // 매번 방문 체크판 새로 만들기
        vector<int> s; // 스택 역할을 할 벡터 (LIFO: 후입선출)

        // 시작점 i에서 갈 수 있는 첫 번째 목적지들을 스택에 넣기
        for (int next : adj[i]) {
            s.push_back(next);
            visited[next] = true;
        }

        // 스택이 빌 때까지 탐색 (비재귀 DFS)
        while (!s.empty()) {
            int now = s.back(); // 맨 뒤(위)에 있는 것 확인
            s.pop_back();       // 꺼내기

            // 현재 위치(now)에서 갈 수 있는 다음 목적지 확인
            for (int next : adj[now]) {
                if (!visited[next]) {
                    visited[next] = true;
                    s.push_back(next);
                }
            }
        }

        // 3. i에서 출발해서 도달 가능했던 곳들(visited) 출력
        for (int j = 0; j < N; j++) {
            if (visited[j]) cout << 1 << " ";
            else cout << 0 << " ";
        }
        cout << "\n";
    }

    return 0;
}

Embed on website

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