Skip to content

Commit

Permalink
Merge pull request #32 from AlgoLeadMe/8-mong3125
Browse files Browse the repository at this point in the history
8-mong3125
  • Loading branch information
mong3125 authored Mar 19, 2024
2 parents 22050f6 + b065248 commit 78e6d12
Showing 1 changed file with 84 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class BOJ1260_DFS์™€BFSํ”„๋กœ๊ทธ๋žจ {

static ArrayList<Integer>[] edges;
static boolean[] visited;
static StringBuilder answer = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());

int n = Integer.parseInt(st.nextToken()); // ๋…ธ๋“œ ์ˆ˜
int m = Integer.parseInt(st.nextToken()); // ๊ฐ„์„  ์ˆ˜
int v = Integer.parseInt(st.nextToken()); // ์ถœ๋ฐœ ๋…ธ๋“œ

edges = new ArrayList[n + 1]; // ๊ฐ„์„  ๋ฐฐ์—ด
for (int i = 0; i < n + 1; i++) {
edges[i] = new ArrayList<>();
}

// ๊ฐ„์„  ์—ฐ๊ฒฐ
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());

edges[a].add(b);
edges[b].add(a);
}

for (int i = 0; i < n + 1; i++) {
Collections.sort(edges[i]);
}

visited = new boolean[n + 1]; // ๋ฐฉ๋ฌธ ์—ฌ๋ถ€ ๋ฐฐ์—ด
dfs(v);
answer.append('\n');

visited = new boolean[n + 1];
bfs(v);
answer.append('\n');

System.out.print(answer);
}

public static void dfs(int now) {
answer.append(now);
answer.append(' ');

visited[now] = true;

for (int next : edges[now]) {
if (!visited[next]) {
dfs(next);
}
}
}

public static void bfs(int start) {
Queue<Integer> queue = new LinkedList<>();

// ์‹œ์ž‘ ๋…ธ๋“œ ์‚ฝ์ž…ํ•˜๊ธฐ
queue.add(start);
visited[start] = true;

// ํ๊ฐ€ ๋นŒ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
while (!queue.isEmpty()) {
int now = queue.poll();
answer.append(now);
answer.append(' ');

// now์— ์—ฐ๊ฒฐ๋œ node๋“ค์„ queue์— ์‚ฝ์ž…ํ•œ๋‹ค.
for (int next : edges[now]) {
if (!visited[next]) {
queue.add(next);
visited[next] = true;
}
}
}
}
}

0 comments on commit 78e6d12

Please sign in to comment.