DFS/BFS 기본 구조를 연습해볼수있는 문제였다.
인접리스트 방식으로 구현하였으며 작은수를 기준으로 탐색을 하여야 했기때문에 메인함수에서 sort함수를 적용하고 시작하였다.
#include <string>
#include <vector>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
int N; //정점갯수
int M; //간선갯수
int answer;
bool visited[1002];
bool used[1002];
vector<int> graph[1002];
void dfs(int x) {
used[x] = true;
cout << x << " ";
for (int i = 0; i < graph[x].size(); i++) {
int y = graph[x][i];
if (!used[y]) dfs(y);
}
}
void bfs(int start) {
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int a = q.front();
q.pop();
cout << a << " ";
for (int i = 0; i < graph[a].size(); i++) {
int y = graph[a][i];
if (!visited[y]) {
visited[y] = true;
q.push(y);
}
}
}
}
int main() {
cin.tie(NULL);
cout.tie(NULL);
ios::sync_with_stdio(false);
int start = 0;
cin >> N >> M >> start;
for (int i = 0; i < M; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
for (int i = 0; i < N; i++) {
sort(graph[i].begin(), graph[i].end());
}
dfs(start);
cout << endl;
bfs(start);
return 0;
}
tie랑 sync랑 순서를 바꿔도 되는 건가요?