-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #32 from AlgoLeadMe/8-mong3125
8-mong3125
- Loading branch information
Showing
1 changed file
with
84 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} | ||
} | ||
} |