less than 1 minute read

문제 풀이 방식

  • 재귀 함수 사용할때 전위/후위 연산자 사용에 유의하자. (주석 참고)
  • println 사용시 시간 초과에 유의하자.
  • DFS

문제 풀이 (Java)

import java.io.BufferedReader;  
import java.io.InputStreamReader;  
import java.util.StringTokenizer;  
  
public class boj15651 {  
    static int N, M;  
    static int[] foo;  
    static StringBuilder sb = new StringBuilder();  
    public static void main(String[] args) throws Exception {  
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
        StringTokenizer st = new StringTokenizer(br.readLine());  
  
        N = Integer.parseInt(st.nextToken());  
        M = Integer.parseInt(st.nextToken());  
  
        foo = new int[M];  
  
        DFS(0);  
        System.out.print(sb);  
    }  
  
    public static void DFS(int depth){  
        if (depth == M){  
            // 탐색 종료 조건 : 길이가 M            printArray(foo);  
            return;  
        }  
  
        // 재귀 호출을 통한 DFS 구현  
        for(int i = 1; i <= N; i++){  
  
            foo[depth] = i;  
            DFS(depth+1);  
  
        }  
  
    }  
  
    public static void printArray(int[] array){  
  
        for(int i = 0; i < array.length ; i++){  
            sb.append(foo[i] + " ");  
        }  
        sb.append('\n');  
    }  
  
}

Leave a comment