코드
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
int N, M, S;
vector<int>adjList[1001];
bool isVisited[1001] = { false, };
stack<int> st;
queue<int> que;
void dfs(int V)
{
st.push(V);
while (!st.empty())
{
int cur = st.top();
st.pop();
if (isVisited[cur]) { continue; }
isVisited[cur] = true;
cout << cur << " ";
for (int i = adjList[cur].size() - 1; i >= 0; i--)
{
int next = adjList[cur][i];
st.push(next);
}
}
}
void bfs(int V)
{
que.push(V);
while (!que.empty())
{
int cur = que.front();
que.pop();
if (isVisited[cur]) { continue; }
isVisited[cur] = true;
cout << cur << " ";
for (int i = 0; i < adjList[cur].size(); i++)
{
int next = adjList[cur][i];
que.push(next);
}
}
}
int main(void)
{
cin >> N >> M >> S;
for (int i = 0; i < M; i++)
{
int u, v;
cin >> u >> v;
adjList[u].push_back(v);
adjList[v].push_back(u);
}
for (int i = 0; i < 1001; i++)
sort(adjList[i].begin(), adjList[i].end());
dfs(S);
cout << endl;
fill_n(isVisited, 1001, false);
bfs(S);
return 0;
}
728x90
'알고리즘(C++) > 백준 문제풀이(C++)' 카테고리의 다른 글
2178 미로탐색 (0) | 2023.05.06 |
---|---|
1149 RGB 거리 (0) | 2023.05.06 |
2606 바이러스 (0) | 2023.05.06 |