본문 바로가기

카테고리 없음

[java] 백트래킹 기본구현코드

import java.io.*;
import java.util.*;

public class Main{
	static int arr[];
	static boolean visit[];
	static int a,b;
	static StringBuilder sb;
	public static void main(String[] args) throws IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer(br.readLine());
		a=Integer.parseInt(st.nextToken());
		b=Integer.parseInt(st.nextToken());
		arr=new int[b];
		visit=new boolean[a];
		sb=new StringBuilder();
		DFS(0);
		System.out.println(sb);
		
		
	}
	private static void DFS(int depth) {
		if(depth==b) {
			for(int date:arr) {
				sb.append(date+" ");
			}
			sb.append("\n");
			return;
		}
		for(int i=0;i<a;i++) {
			if(!visit[i]) {
				visit[i]=true;
				arr[depth]=i+1;
				DFS(depth+1);
				visit[i]=false;
			}
		}
		
	}
}