๐ ๋ฐฑ์ค 15654๋ฒ - N๊ณผ M (5)
๐ ๋ฐฑ์ค 15654๋ฒ - N๊ณผ M (5) | DFS ์์ด ๋ก์ง ์์ ์ ๋ณต
๐ ๋ฌธ์ ์์ฝ
- ์์ฐ์ N๊ฐ๊ฐ ์ฃผ์ด์ง๊ณ , ๊ทธ ์ค M๊ฐ๋ฅผ ์ค๋ณต ์์ด ๊ณจ๋ผ ์์ด์ ๋ง๋ค์ด์ผ ํจ
- ์ถ๋ ฅ์ ์ฌ์ ์์ผ๋ก ์ค๋ฆ์ฐจ์
- ์:
1 2
,2 1
,1 3
,3 1
,2 3
, โฆ
๐ฅ ์์ ์ ๋ ฅ
3 2
3 1 2
์ ๋ ฌ๋๋ฉด: [1, 2, 3]
โ ์ด ์ซ์๋ค๋ก M = 2์ธ ์์ด์ ๋ง๋ค์ด์ผ ํจ (์ค๋ณต โ)
โ ํต์ฌ ํฌ์ธํธ
ํฌ์ธํธ | ์ค๋ช |
---|---|
์ค๋ณต ํ์ฉ? | โ ์๋จ |
์ ๋ ฌ ํ์? | โ ์ฌ์ ์ ์ถ๋ ฅ์ ์ํด ์ค๋ฆ์ฐจ์ ์ ๋ ฌ |
์๋ฃ๊ตฌ์กฐ | visited[] ๋ฐฐ์ด๋ก ์ค๋ณต ์ฒดํฌ |
๋ฐฑํธ๋ํน | ์ฌ์ฉํ ์ซ์ ๋๋๋ฆฌ๊ธฐ |
๐ง DFS ๊ตฌ์กฐ ์ดํดํ๊ธฐ
dfs(depth)
depth == M
โ ์ถ๋ ฅfor i in 0 ~ N-1
visited[i] == false
โ ์ฌ์ฉ ๊ฐ๋ฅ- ์ซ์ ์ ์ฅ ํ
dfs(depth + 1)
- ๋ฐฑํธ๋ํน:
visited[i] = false
๋ณต์
๐ ์๋ฎฌ๋ ์ด์ ์ผ๋ก ์์ ์ดํดํ๊ธฐ
๐ฏ ์ด๊ธฐ ์ํ
N = 3, M = 2
์
๋ ฅ: 3 1 2 โ ์ ๋ ฌ: [1, 2, 3]
dfs(0) ์์
โ dfs(0)
- depth = 0
- visited =
[false, false, false]
- output =
[]
i = 0 โ 1 ์ฌ์ฉ
โ visited[0] = true
โ output[0] = 1
โ dfs(1) ํธ์ถ
โ dfs(1)
- depth = 1
- output =
[1, _]
- visited =
[true, false, false]
i = 1 โ 2 ์ฌ์ฉ
โ output = [1, 2]
โ visited = [true, true, false]
โ dfs(2)
โ
์ถ๋ ฅ โ 1 2
๐ ๋ฐฑํธ๋ํน
โ visited[1] = false
i = 2 โ 3 ์ฌ์ฉ
โ output = [1, 3]
โ dfs(2)
โ
์ถ๋ ฅ โ 1 3
๐ visited[2] = false
๐ visited[0] = false
๐ ๋ค์ ๋ฃจํ ์งํ
i = 1 โ 2 ์ฌ์ฉ
โ output = [2, _]
โ visited = [false, true, false]
โ dfs(1)
โ i = 0 โ 1 ์ฌ์ฉ โ output = [2, 1]
โ
์ถ๋ ฅ โ 2 1
โ i = 2 โ 3 ์ฌ์ฉ โ output = [2, 3]
โ
์ถ๋ ฅ โ 2 3
๐ ๋ง์ง๋ง ๋ฃจํ
i = 2 โ 3 ์ฌ์ฉ
โ output = [3, _]
โ dfs(1)
โ i = 0 โ 1 ์ฌ์ฉ โ [3, 1]
โ
์ถ๋ ฅ โ 3 1
โ i = 1 โ 2 ์ฌ์ฉ โ [3, 2]
โ
์ถ๋ ฅ โ 3 2
โ ์ต์ข ์ถ๋ ฅ
1 2
1 3
2 1
2 3
3 1
3 2
โ ์ ๋ต ์ฝ๋
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Back_15654 {
static int N, M;
static int[] input, output;
static boolean[] visited;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
input = new int[N];
output = new int[M];
visited = new boolean[N];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < N; i++) input[i] = Integer.parseInt(st.nextToken());
Arrays.sort(input); // ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
dfs(0);
System.out.print(sb);
}
static void dfs(int depth) {
if (depth == M) {
for (int i = 0; i < M; i++) sb.append(output[i]).append(" ");
sb.append("\n");
return;
}
for (int i = 0; i < N; i++) {
if (!visited[i]) {
visited[i] = true;
output[depth] = input[i];
dfs(depth + 1);
visited[i] = false;
}
}
}
}
๐ง ๋ง๋ฌด๋ฆฌ ์ ๋ฆฌ
ํญ๋ชฉ | ์ค๋ช |
---|---|
DFS ๊ธฐ๋ฐ | ๋ชจ๋ ์์ด ์์ฑ |
visited | ์ค๋ณต ๋ฐฉ์ง๋ฅผ ์ํ ์ฒดํฌ |
์ค๋ฆ์ฐจ์ ์ถ๋ ฅ | Arrays.sort() ์ฌ์ฉ |
๋ฐฑํธ๋ํน | ์ฌ์ฉํ ์ซ์ ๋ณต์ ํ ๋ค์ ๊ฒฝ์ฐ ํ์ |
๋๊ธ๋จ๊ธฐ๊ธฐ