-
DFS와 BFSAlgorithm/BOJ 2020. 2. 18. 17:171234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374//1260 - DFS와 BFS#include <iostream>#include <vector>#include <queue>#include <algorithm>using namespace std;int N, M, S;vector<vector<int>> adj;vector<bool> visit;void init(){cin >> N >> M >> S;adj = vector<vector<int>>(N+1);visit = vector<bool>(N+1, false);int x, y;for(int i = 0; i<M; ++i){cin >> x >> y;adj[x].push_back(y);adj[y].push_back(x);}for(int i = 1; i<=N; ++i)sort(adj[i].begin(), adj[i].end());}void dfs(int here){cout << here << " ";visit[here] = true;for(int i = 0; i<adj[here].size(); ++i){int there = adj[here][i];if(!visit[there])dfs(there);}}void bfs(){visit = vector<bool>(N+1, false);queue<int> q;q.push(S);visit[S] = true;while(!q.empty()){int here = q.front();q.pop();cout << here << " ";for(int i = 0; i<adj[here].size(); ++i){int there = adj[here][i];if(!visit[there]){visit[there] = true;q.push(there);}}}}int main(){ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);init();dfs(S);cout << "\n";bfs();}
cs 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
기본 DFS, BFS문제 입니다!
'Algorithm > BOJ' 카테고리의 다른 글
외판원 순회 - 2098 (0) 2020.02.19 등산 - 1486 (0) 2020.02.18 거의 최단 경로 - 5719 (0) 2020.02.18 특정한 최단 경로 - 1504 (0) 2020.02.18 집합 - 11723 (0) 2020.02.17