반응형
✏️ 문제 링크
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⭐
반응형
'Algorithm 💫 > Problem Solving' 카테고리의 다른 글
[백준] 2178번: 미로 탐색 / C++ (0) | 2021.09.16 |
---|---|
[백준] 1303번: 전쟁 - 전투 / C++ (0) | 2021.09.16 |
[백준] 1916: 최소비용 구하기/ 다익스트라 / C++ ⭐ (0) | 2021.09.15 |
[백준] 1806번: 부분합/ C++ ⭐ (0) | 2021.09.14 |
[백준] 1700번: 멀티탭 스케줄링 / C++ (0) | 2021.09.14 |
댓글