본문 바로가기
Algorithm 💫/Problem Solving

[백준] 1260번: DFS와 BFS / C++

by 돼지고기맛있다 2021. 9. 15.
반응형

✏️ 문제 링크

https://www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

 

 

✏️ 문제 설명 (더보기 클릭 👆🏻)

 

✏️ 문제 풀이

dfs와 bfs의 기본이 되는 문제! 😘

 

 

✏️ 문제 코드

#include <bits/stdc++.h>

using namespace std;

int vec[1001][1001];
vector<int> vis(1001, false);
int N, M, V; 

void dfs(int v){
    
    cout<<v<<" ";
    for(int i=0; i<=N; i++){
        if(vec[v][i]){
            int nxt=i;
            if(!vis[nxt]) { vis[nxt]=true; dfs(nxt);}
        }
        
    }
}
void bfs(int v){

    queue<int> q;
    q.push(v);
    vis[v]=true;
    while(!q.empty()){
        
        int c=q.front(); q.pop();
        cout<<c<<" ";
        
        for(int i=0; i<=N; i++){
            if(vec[c][i]){
                int nxt=i;
                if(!vis[nxt]) {vis[nxt]=true; q.push(nxt);}
            }
            
        }
    }

}
int main(){
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    cin>>N>>M>>V;
    
    while(M--){
        int v, w;cin>>v>>w;
        vec[v][w]=true;
        vec[w][v]=true;
    }
    
    vis[V]=true;
    dfs(V);
    cout<<"\n";
    for(int i=0; i<=N; i++) vis[i]=false;
    bfs(V);
    
    
    return 0;
}

 

 

 

 ⭐ if feedback and question : comment please⭐  

 

 

 

 

 

반응형

댓글