알고리즘/DFS & BFS

백준[1260] DFS와 BFS

HJ39 2023. 1. 11. 01:28

앞에서 풀었던 문제들(오름차순 정렬)을 한번에 해보는 문제이다.

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);
    
}