728x90
์์ ์ ์ ์ค์ ์ ์ ๋ฌธ์ . ํ๋ฉด DFS์ BFS์ ๊ฐ๋ ์ ๋ํด์ ๋ค์ ์ก์ ์ ์๋ค.
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
int main() {
int vertex = 0;
int edge = 0;
int first = 0;
cin >> vertex >> edge >> first;
vector<vector<int>> adj(vertex+1);
vector<int> visited(vertex+1, 0);
for(int i = 0 ; i < edge ; i++) {
int one = 0, two =0 ;
cin >> one >> two;
adj[one].push_back(two);
adj[two].push_back(one);
}
for(int i = 1 ; i <= vertex ; i++) {
sort(adj[i].begin(), adj[i].end());
}
// for(int i =1 ; i <= vertex ; i++) {
// cout << "[ " << i << " ] ";
// for(int j =0 ; j < adj[i].size() ; j++) {
// cout << adj[i][j] << " ";
// }
// cout << endl;
// }
stack<int> s;
s.push(first);
visited[first] = 1;
cout << first << " ";
while(!s.empty()) {
int node = s.top();
s.pop();
for(int i = 0 ; i < adj[node].size() ; i++) {
if(visited[adj[node][i]] == 0) {
cout << adj[node][i] << " ";
visited[adj[node][i]] = 1;
s.push(node);
s.push(adj[node][i]);
break;
}
}
}
cout << endl;
vector<int> visited1(vertex+1, 0);
queue<int> q;
q.push(first);
visited1[first] = 1;
cout << first << " ";
while(!q.empty()) {
int node = q.front();
q.pop();
for(int i =0 ; i < adj[node].size() ; i++) {
if(visited1[adj[node][i]] == 0) {
visited1[adj[node][i]] = 1;
cout << adj[node][i] << " ";
q.push(adj[node][i]);
}
}
}
return 0;
}
'๐ Self Study > ๐ BaekJoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค BaekJoon (์คํํธ๋งํฌ, 5014๋ฒ) C++ (0) | 2022.01.11 |
---|---|
๋ฐฑ์ค BaekJoon (์จ๋ฐ๊ผญ์ง, 1697๋ฒ) C++ (0) | 2022.01.11 |
๋ฐฑ์ค BaekJoon (ํ ๋งํ , 7569๋ฒ) C++ (0) | 2022.01.11 |
๋ฐฑ์ค BaekJoon(์ด์ ๊ณ์ฐ, 2644๋ฒ) C++ (0) | 2022.01.10 |
๋ฐฑ์ค BaekJoon (๋ฐ์ด๋ฌ์ค, 2606) C++ (0) | 2022.01.05 |