알고리즘/백준

[백준] N과M(1)

hongeeii 2023. 4. 8.
728x90
반응형

백트래킹을 이용하여 품  

 

package com.example.demo.chaper01.item08.outerclass;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;

public class N과M {
	private static boolean[] visit;
	private static Stack<Integer> stack = new Stack<>();
	private static StringBuilder sb = new StringBuilder();

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		String line = br.readLine();

		StringTokenizer st = new StringTokenizer(line);

		int n = Integer.parseInt(st.nextToken());
		int m = Integer.parseInt(st.nextToken());

		visit = new boolean[n + 1];

		bt(n, m);

		System.out.println(sb);
	}

	private static void bt(int n, int m) {
		if (stack.size() == m) {
			for (int s : stack) {
				sb.append(s + " ");
			}
			sb.append("\n");
			return;
		}

		for (int i = 1; i <= n; i++) {
			if (!visit[i]) {
				visit[i] = true;
				stack.add(i);
				bt(n, m);
				visit[i] = false;
				stack.pop();
			}
		}
	}
}
728x90
반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준] N과M(6)  (0) 2023.04.10
[백준] N과M(5)  (0) 2023.04.10
[백준] N과M(4)  (0) 2023.04.10
[백준] N과M(3)  (0) 2023.04.10
[백준] N과M(2)  (0) 2023.04.08

추천 글