
import java.util.Scanner;
public class N과M_2 {
static int N, M;
static int[] ARR;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
ARR = new int[N + 1];
for (int i = 1; i < N + 1; i++)
ARR[i] = i;
dfs(1, 0, new int[M]);
}
public static void dfs(int num, int depth, int[] arr) {
if (num > N)
return;
if (depth == M) {
for (int i : arr)
System.out.print(i + " ");
System.out.println();
return;
}
arr[depth] = num;
for (int i = num; i < N + 1; i++)
dfs(i + 1, depth + 1, arr);
}
}
진짜 무시무시한 녀석이다..import java.util.Scanner;
public class N과M_2 {
static int N, M;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
dfs(1, 0, new int[M]);
}
public static void dfs(int num, int depth, int[] arr){
if(depth == M){
for(int i : arr)
System.out.print(i + " ");
System.out.println();
return;
}
for(int i=num; i<N+1; i++){
arr[depth] = i;
dfs(i + 1, depth + 1, arr);
}
}
}
문제를 복기하다가 헷갈리는 지점을 찾았다.
어떻게 dfs(1, 0, new arr[])로 모든 노드를 다 탐색했지? 하는 의구심. 역시 dfs는 진짜진짜 헷갈린다.
직접 그려보면서 이해를 해봤다. 필기가 너무 더러워서 올려놓진 않겠지만,for(int i=num; i<N+1; i++){ arr[depth] = i; dfs(i + 1, depth + 1, arr); }에서 잘보면 arr[depth] = i 다. 그러니까 depth가 0으로 시작하기 때문에, 탐색을 시작하는 노드가 i에 따라 바뀌는 것이다. 배열의 첫번째 값이 dfs내의 for문에 의해 계속 상승하는 것.
<arr[depth] = num 을 하게되면 tree 탐색이 똑바로 되겠나.. for문 안의 i로 초기화해주어야한다.> 라고 저 위에 헛똑똑이씨는 이해한줄 알고 넘어가셨다.
코딩테스트를 공부하면서 dfs를 자신있게 코딩했던 적은 생각해보니 graph 탐색이었다. 왜 그 visited배열 찍어가면서 노드 탐색하는 과정..
그리고 dfs를 코딩할때 어려움을 느꼈던 분야는 이 문제와 같이 재귀적으로 알고리즘을 직접 짜야하는 경우, 특히 백트래킹 문제였던 것 같다. 머슬 메모리에 의해 그냥 타이핑하는 dfs가 아니라 직접 설계하는... 생각해보니 삼성그룹 코테 기출문제에서도 dfs에서 애먹었던 문제는 이런쪽이었다.
좋아 넌 내가 정복한다