์ค๋์ ํ์ต ํค์๋
- DFS
๋ฌธ์ - ๋น๊ธฐ๋
ํ์ด
class Solution {
public int solution(String s) {
String[] words = new String[] {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
for(int i = 0; i < words.length; i++) {
if(s.contains(words[i])) {
s = s.replace(words[i], String.valueOf(i));
}
}
return Integer.parseInt(s);
}
}
๋ฌธ์ - ๋ฏธ๋ค๋ฌ
์๊ณ ๋ฆฌ์ฆ ์์ - ๊น์ด ์ฐ์ ํ์ 1
ํ์ด
import java.util.*;
class Main {
public static int[] answer;
public static int n; // ์ ์ ์ ์
public static int m; // ๊ฐ์ ์ ์
public static int r; // ์์ ์ ์
public static boolean[] visited;
public static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
public static int rank;
public static void dfs(int x) {
visited[x] = true;
answer[x] = rank;
for(int i = 0; i < graph.get(x).size(); i++) {
int y = graph.get(x).get(i);
if(!visited[y]) {
rank++;
dfs(y);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
r = sc.nextInt();
rank = 1;
answer = new int[n + 1];
visited = new boolean[n + 1];
for(int i = 0; i <= n; i++) {
graph.add(new ArrayList<Integer>());
}
for(int i = 0; i < m; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
graph.get(x).add(y);
graph.get(y).add(x);
}
for(int i = 0; i < graph.size(); i++) {
Collections.sort(graph.get(i));
}
dfs(r);
for(int i = 1; i < answer.length; i++) {
System.out.println(answer[i]);
}
}
}
- DFS๋ฅผ ๊ณต๋ถํ๊ณ ๊ธฐ๋กํ์ต๋๋ค.
'๐ Study' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[99ํด๋ฝ ์ฝํ ์คํฐ๋] 8์ผ์ฐจ (4) | 2024.11.04 |
---|---|
[99ํด๋ฝ ์ฝํ ์คํฐ๋] 5์ผ์ฐจ (0) | 2024.11.01 |
[99ํด๋ฝ ์ฝํ ์คํฐ๋] 3์ผ์ฐจ (0) | 2024.10.30 |
[99ํด๋ฝ ์ฝํ ์คํฐ๋] 2์ผ์ฐจ (1) | 2024.10.29 |
[99ํด๋ฝ ์ฝํ ์คํฐ๋] 1์ผ์ฐจ (0) | 2024.10.28 |