728x90
문제
그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
입력
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
출력
첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.
간단한 문제이므로 설명은 생략한다. 다만 유의할 점으로는 정점의 번호가 1부터 N까지라는 점과, DFS 호출 후 BFS를 호출하기 전 visited_ 배열을 초기화해야 한다는 점이 있다.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Graph
{
private:
int n_; // number of verteces
vector<vector<int>> adj_mat_; // adjacenct matrix
vector<bool> visited_;
public:
Graph(int n);
void setEdge(int v, int w);
bool isEdge(int v, int w) const;
void clearVisited_();
void dfs(int v);
void bfs(int v);
};
Graph::Graph(int n) : n_(n)
{
adj_mat_.resize(n, vector<int>(n, 0));
visited_.resize(n, false);
}
void Graph::setEdge(int v, int w)
{
adj_mat_[v][w] = 1;
adj_mat_[w][v] = 1;
}
bool Graph::isEdge(int v, int w) const
{
return adj_mat_[v][w] == 1;
}
void Graph::clearVisited_()
{
fill(visited_.begin(), visited_.end(), false);
}
void Graph::dfs(int v)
{
visited_[v] = true;
cout << v + 1 << " "; // 1-base indexing
for (int w = 0; w < n_; w++)
if (isEdge(v, w) && !visited_[w])
dfs(w);
}
void Graph::bfs(int v)
{
queue<int> q;
visited_[v] = true;
cout << v + 1 << " "; // 1-base indexing
q.push(v);
while (!q.empty())
{
v = q.front();
q.pop();
for (int w = 0; w < n_; w++)
if (isEdge(v, w) && !visited_[w])
{
visited_[w] = true;
cout << w + 1 << " "; // 1-base indexing
q.push(w);
}
}
}
int main()
{
// freopen("input.txt", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N, M, V;
cin >> N >> M >> V;
Graph g(N);
while (M--)
{
int v, w;
cin >> v >> w;
g.setEdge(v - 1, w - 1); // 0-base indexing
}
g.dfs(V - 1); // 0-base indexing
cout << '\n';
g.clearVisited_();
g.bfs(V - 1); // 0-base indexing
return 0;
}
728x90
'Baekjoon' 카테고리의 다른 글
[Baekjoon] 2630: 색종이 만들기 - (C3, S2) Recursion (0) | 2025.01.16 |
---|---|
[Baekjoon] 1541: 잃어버린 괄호 - (C3, S2) string (2) | 2025.01.16 |
[Baekjoon] 1012: 유기농 배추 - (C3, S2) BFS (1) | 2025.01.14 |
[Baekjoon] 17626: Four Squares - (C3, S3) DP (0) | 2025.01.14 |
[Baekjoon] 11727: 2xn 타일링 2 - (C3, S3) DP (0) | 2025.01.14 |