[Algorithm] DFS & BFS
2020. 3. 16. 17:15ㆍProblem solving/Algorithm
https://www.acmicpc.net/problem/1260
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
int graph[1001][1001];
bool visited[1001];
int n, m, v;
void dfs(int start) {
memset(visited, false, sizeof(visited));
stack<int> s;
s.push(start);
while (!s.empty()) {
int current_node = s.top();
s.pop();
if (!visited[current_node]) {
visited[current_node] = true;
cout << current_node << " ";
for (int i = n; i > 0; i--)
if (!visited[i] && graph[current_node][i] == 1) s.push(i);
}
}
cout << "\n";
}
void bfs(int start) {
memset(visited, false, sizeof(visited));
queue<int> q;
q.push(start);
while (!q.empty()) {
int current_node = q.front();
q.pop();
if (!visited[current_node]) {
visited[current_node] = true;
cout << current_node << " ";
for (int i = 1; i <= n; i++)
if (!visited[i] && graph[current_node][i] == 1) q.push(i);
}
}
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> m >> v;
for (int i = 0; i < m; i++) {
int s, e;
cin >> s >> e;
graph[s][e] = 1;
graph[e][s] = 1;
}
dfs(v);
bfs(v);
return 0;
}
'Problem solving > Algorithm' 카테고리의 다른 글
벨만 포드 알고리즘 (Bellman-Ford algorithm) (0) | 2020.03.25 |
---|---|
다익스트라 알고리즘(Dijkstra Algorithm) (0) | 2020.03.22 |
[Algorithm] 이분 탐색 (0) | 2020.03.03 |
[Algorithm] 최대공약수, 최소공배수 구하기 (0) | 2019.12.04 |
[Algorithm] 소수 구하기 (0) | 2019.12.03 |