728x90
https://www.acmicpc.net/problem/15649
package BKD_0x0C_BackTracking;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ_15649 {
// 1부터 N까지의 자연수 중에서 중복 없이 M개를 고르는 수열
static int N;
static int M;
static boolean[] visit = new boolean[N];
// 재귀를 진행하면서 이미 방문한 노드라면 다음 노드를 탐색하도록 하기 위함. == 유만한 노드인지 검사
//방문 상태를 확인하기 위한 배열
static int[] arr = new int[M];
// 탐색 과정에서 값을 담을 int 배열
public static void dfs(int N, int M, int depth){
if(depth ==M){
// 재귀 깊이가 M 과 같아지면 탐색 과정에서 담았던 배열을 출력
for(int val : arr){
System.out.print(val+" ");
}
System.out.println();
return;
}
for(int i=0;i<N;i++){
if(visit[i] == false){
visit[i] = true;
arr[depth] = i+1;//깊이를 인덱스로 현재 값을 저장.
dfs(N,M,depth+1);
visit[i] = false;
}
}
return;
}
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
N =Integer.parseInt(st.nextToken());
M =Integer.parseInt(st.nextToken());
arr = new int[M];
visit = new boolean[N];
dfs(N,M,0);
}
}
참고 url : https://st-lab.tistory.com/114
개념 숙지를 위해 그냥 거의 따라 쳤다고 봐도 무방무방
728x90
'🐣 알고리즘 삐약 > 💻 백준 삐약' 카테고리의 다른 글
86 삐약 : 백준 15652| N과 M (4) [바킹독| 백트래킹 |JAVA] (0) | 2024.08.14 |
---|---|
84 삐약 : 백준 15650| N과 M (2) [바킹독| 백트래킹 |JAVA] (0) | 2024.08.13 |
82 삐약 : 백준 13458| 시험감독 [삼성 SW 역량테스트|JAVA] (0) | 2024.08.08 |
81 삐약 : 백준 1149| RGB거리 [바킹독 문제 풀이|DP|JAVA] (0) | 2024.06.19 |
80 삐약 : 백준 14501| 퇴사 [바킹독 문제 풀이|DP|JAVA] (0) | 2024.06.18 |