-
그래프_백준_DFS와 BFS_1260Algorithm 2018. 8. 30. 13:12
구현
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465#include <iostream>#include <algorithm>#include <stack>#include <queue>#include <vector>#include<cstring>using namespace std;vector <int> a[1001];bool check[1001];void dfs(int x) {check[x] = true;printf("%d ", x);for (int i = 0; i < a[x].size(); i++) {int next = a[x][i];if (check[next] == false) {check[next] = true;dfs(next);}}}void bfs(int start) {memset(check, false, sizeof(check));queue <int> q;check[start] = true;q.push(start);while (!q.empty()) {int top = q.front();q.pop();printf("%d ", top);for (int i = 0; i < a[top].size(); i++) {int tmp = a[top][i];if (check[tmp] == false) {q.push(tmp);check[tmp] = true;}}}}int main() {int n, e, start;int u, v;scanf("%d %d %d", &n, &e, &start);for (int i = 1; i <= e; i++) {scanf("%d %d", &u, &v);a[u].push_back(v);a[v].push_back(u);}for (int i = 1; i <= n; i++) {sort(a[i].begin(), a[i].end());}dfs(start);printf("\n");bfs(start);printf("\n");}cs 'Algorithm' 카테고리의 다른 글
그래프_백준_이분 그래프_1707 (0) 2018.08.31 그래프_백준_연결 요소_11724 (0) 2018.08.30 그래프_백준_그래프의 탐색 (0) 2018.08.23 그래프_백준_이론 (0) 2018.08.22 정렬_백준_K번째 수_11004 (0) 2018.08.21