코딩성장스토리

백준 1260번:DFS와 BFS 본문

백준 코딩

백준 1260번:DFS와 BFS

까르르꿍꿍 2021. 10. 1. 20:04

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<iostream>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#define PI 3.1415926535
using namespace std;
bool check1[1001] = { 0 };
bool check2[1001] = { 0 };
vector<int> d[1002];

void dfs(int a) {                        //dfs함수 정리
	check1[a] = true;
	cout << a << ' ';
	for (int i = 0; i < d[a].size(); i++) {
		int next = d[a][i];
		if (check1[next] == false)
			dfs(next);
	}
}
void bfs(int a) {                      //bfs함수정리
	queue<int> q;
	check2[a] = true;
	q.push(a);
	while (!q.empty()) {          
		int b = q.front();
		q.pop();
		cout << b << ' ';
		for (int i = 0; i < d[b].size(); i++) {
			int n = d[b][i];
			if (check2[n] == false) {
				check2[n] = true;
				q.push(n);
			}
		}
	}
}
int main()
{	
	int n=0, m=0,v=0;
	cin >> n >> m >> v;
	while (m--) {
		int a, b;
		cin >> a >> b;
		d[a].push_back(b);
		d[b].push_back(a);
	}
	for (int i = 1; i <= n; i++){              //여러개 동시에 정점이 있을때에 작은것부터 하기위해 정렬
		sort(d[i].begin(), d[i].end());}
	dfs(v);
	cout << '\n';
	bfs(v);
	return 0;
}