앞에서 풀었던 문제들(오름차순 정렬)을 한번에 해보는 문제이다.
DFS, BFS 코드를 알고 있다면 손 쉽게 풀 수 있다.
□ 소스 코드
#include <bits/stdc++.h>
int dbN,dbM,dbR;
vector<int> dbList[1001];
bool dbVisited[1001]{false};
void dfs1260(int v){
    
    if(dbVisited[v])
        return;
    
    dbVisited[v] = true;
    cout<< v <<" ";
    
    for(int i=0;i<(int)dbList[v].size();i++){
        int next = dbList[v][i];
        dfs1260(next);
    }
}
void bfs1260(int v){
    queue<int> bfsQueue;
    
    dbVisited[v] = true;
    bfsQueue.push(v);
    
    while(!bfsQueue.empty()){
        int front = bfsQueue.front();
        bfsQueue.pop();
        cout<<front<<" ";
        for(int i=0;i<(int)dbList[front].size();i++){
            int next = dbList[front][i];
            
            if(!dbVisited[next]){
                dbVisited[next] = true;
                bfsQueue.push(next);
            }
        }
    }
}
void DFSAndBFS(){
    scanf("%d%d%d",&dbN,&dbM,&dbR);
    
    for(int i=0;i<dbM;i++){
        int dbin1,dbin2;
        scanf("%d%d",&dbin1,&dbin2);
        dbList[dbin2].push_back(dbin1);
        dbList[dbin1].push_back(dbin2);
    }
    
    
    for(int i=1;i<=dbN;i++){
        sort(dbList[i].begin(),dbList[i].end());
    }
    for(int i=1;i<=dbN;i++){
        for(int j=0;j<dbList[i].size();j++){
            printf("%d ",dbList[i][j]);
        }
        cout<<endl;
    }
    cout<<endl;
    
    dfs1260(dbR);
    cout<<endl;
    fill_n(dbVisited, 1001, false);
    bfs1260(dbR);
    
}'알고리즘 > DFS & BFS' 카테고리의 다른 글
| 백준 [1012] 유기농 배추 (0) | 2023.01.11 | 
|---|---|
| 백준[2667] 단지번호붙이기 (0) | 2023.01.11 | 
| 백준[2606] 바이러스 (0) | 2023.01.10 | 
| 백준[24445] 알고리즘 수업 - 너비 우선 탐색 2 (0) | 2023.01.10 | 
| 백준[24444] 알고리즘 수업 - 너비 우선 탐색 1 (0) | 2023.01.10 |