🐣 알고리즘 삐약/💻 백준 삐약
83 삐약 : 백준 15649| N과 M (1) [바킹독| 백트래킹 |JAVA]
우주수첩
2024. 8. 13. 16:47
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
[백준] 15649번 : N과 M (1) - JAVA [자바]
www.acmicpc.net/problem/15649 15649번: N과 M (1) 한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열
st-lab.tistory.com
개념 숙지를 위해 그냥 거의 따라 쳤다고 봐도 무방무방
728x90