Skip to content

Commit da8173e

Browse files
committed
[Silver II] Title: 알고리즘 수업 - 깊이 우선 탐색 1, Time: 196 ms, Memory: 8984 KB -BaekjoonHub
1 parent 5b47132 commit da8173e

2 files changed

Lines changed: 44 additions & 29 deletions

File tree

백준/Silver/24479. 알고리즘 수업 - 깊이 우선 탐색 1/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44

55
### 성능 요약
66

7-
메모리: 19000 KB, 시간: 220 ms
7+
메모리: 8984 KB, 시간: 196 ms
88

99
### 분류
1010

1111
깊이 우선 탐색, 그래프 이론, 그래프 탐색, 정렬
1212

1313
### 제출 일자
1414

15-
2025년 3월 4일 14:34:47
15+
2025년 3월 4일 21:38:43
1616

1717
### 문제 설명
1818

백준/Silver/24479. 알고리즘 수업 - 깊이 우선 탐색 1/알고리즘 수업 - 깊이 우선 탐색 1.cc

Lines changed: 42 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,54 @@
11
#include <iostream>
2+
#include <vector>
3+
#include <stack>
24
#include <algorithm>
35

4-
#define MAX 200001
56
using namespace std;
67

7-
vector<int> graph[MAX];
8-
int visited[MAX];
9-
int answer[MAX];
10-
int seq = 1;
11-
12-
void dfs(int n_n, int depth) {
13-
sort(graph[n_n].begin(), graph[n_n].end());
14-
for (int nn_n : graph[n_n]) {
15-
if (visited[nn_n]) continue;
16-
answer[nn_n] = ++seq;
17-
visited[nn_n] = 1;
18-
dfs(nn_n, depth+1);
8+
int main()
9+
{
10+
int N, M, R;
11+
cin >> N >> M >> R; // 정점수, 간선 수, 시작 정점
12+
13+
vector<vector<int> > edges(N);
14+
vector<bool> visited(N, false);
15+
vector<int> orders(N, 0);
16+
17+
int source, destination;
18+
for (int i = 0; i < M; i++)
19+
{
20+
cin >> source >> destination;
21+
edges[source-1].push_back(destination);
22+
edges[destination-1].push_back(source);
1923
}
20-
}
2124

22-
int main() {
23-
int N, M, R;
24-
cin >> N >> M >> R;
25-
for (int i = 0; i < M; i++) {
26-
int u, v;
27-
cin >> u >> v;
28-
graph[u].push_back(v);
29-
graph[v].push_back(u);
25+
for (int i = 0; i < N; i++)
26+
{
27+
sort(edges[i].begin(), edges[i].end(), std::greater<int>());
28+
}
29+
30+
stack<int> node_s;
31+
node_s.push(R);
32+
33+
int order = 1;
34+
while (!node_s.empty())
35+
{
36+
int current_node = node_s.top(); node_s.pop();
37+
if (visited[current_node-1]) continue;
38+
visited[current_node-1] = true;
39+
orders[current_node-1] = order++;
40+
for (auto adj_node: edges[current_node-1])
41+
{
42+
if (!visited[adj_node-1])
43+
{
44+
node_s.push(adj_node);
45+
}
46+
}
3047
}
3148

32-
visited[R] = 1;
33-
answer[R] = seq;
34-
dfs(R, 0);
35-
for (int i = 1; i <= N; i++) {
36-
cout << answer[i] << '\n';
49+
for (auto result: orders)
50+
{
51+
cout << result << '\n';
3752
}
3853

3954
return 0;

0 commit comments

Comments
 (0)