PS/백준

[백준 | 15649] N과 M(1) - Java

yaho!! 2024. 8. 14. 00:39

📃 제출

import java.util.Scanner;

public class Main {
    public static boolean[] visited;
    public static int[] arr;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int M = sc.nextInt();

        visited = new boolean[N];
        arr = new int[M];
        dfs(N, M, 0);
    }

    public static void dfs(int N, int M, int depth) {
        if (depth == M) {
            for (int i : arr) {
                System.out.print(i + " ");
            }
            System.out.println();
            return;
        }

        for (int i = 0; i < N; i++) {
            if (!visited[i]) {
                visited[i] = true;
                arr[depth] = i + 1;
                dfs(N, M, depth + 1);
                visited[i] = false;
            }
        }
    }
}

✏ 풀이

N = 4, N = 2일때 dfs 메서드 설명