import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static int[] arr;
public static boolean[] visit;
public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
arr = new int[M]; // 임시 순열 값
visit = new boolean[N]; // 노드 방문 여부
dfs(N, M, 0);
bw.flush();
bw.close();
}
public static void dfs(int N, int M, int depth) throws IOException {
if(depth == M) {
for(int val : arr) {
bw.write(val + " ");
}
bw.write("\n");
return;
}
/**
* 노드 방문여부에 따라 재귀 함수 처리
* ex) visit[0](=1) = true일 경우,
* 재귀 함수가 돌면서 1이 아닌 값들을 저장
*/
for(int i=0; i<N; i++) {
if(! visit[i]) {
visit[i] = true;
arr[depth] = i + 1;
dfs(N, M, depth + 1);
// ex) i가 0일 경우 arr[0] = 1, visit[0] = true이므로 arr[1] = 2 출력
visit[i] = false; // 다음 순열 계산을 위해 초기화
}
}
}
}
'Algorithm > 백준' 카테고리의 다른 글
백준 2667 (단지번호붙이기) (0) | 2024.03.21 |
---|---|
백준 11047 (동전 0) (0) | 2024.01.07 |
백준 11399 (ATM) (0) | 2024.01.01 |
백준 17219 (비밀번호 찾기) (0) | 2023.12.26 |
백준 1654 (랜선 자르기) (0) | 2023.12.26 |