PS/BaekJoon

15649 JAVA N๊ณผ M (1)

chaerlo127 2024. 2. 1. 01:42
728x90
 

15649๋ฒˆ: N๊ณผ M (1)

ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ๋ฌธ์ œ์˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์ˆ˜์—ด์„ ์ถœ๋ ฅํ•œ๋‹ค. ์ค‘๋ณต๋˜๋Š” ์ˆ˜์—ด์„ ์—ฌ๋Ÿฌ ๋ฒˆ ์ถœ๋ ฅํ•˜๋ฉด ์•ˆ๋˜๋ฉฐ, ๊ฐ ์ˆ˜์—ด์€ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค. ์ˆ˜์—ด์€ ์‚ฌ์ „ ์ˆœ์œผ๋กœ ์ฆ๊ฐ€ํ•˜๋Š” ์ˆœ์„œ๋กœ ์ถœ๋ ฅํ•ด

www.acmicpc.net

 

 

๐Ÿ€ ๋ฌธ์ œ

์ž์—ฐ์ˆ˜ N๊ณผ M์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ์•„๋ž˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ๊ธธ์ด๊ฐ€ M์ธ ์ˆ˜์—ด์„ ๋ชจ๋‘ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

  • 1๋ถ€ํ„ฐ N๊นŒ์ง€ ์ž์—ฐ์ˆ˜ ์ค‘์—์„œ ์ค‘๋ณต ์—†์ด M๊ฐœ๋ฅผ ๊ณ ๋ฅธ ์ˆ˜์—ด

๐Ÿ€ ์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ N๊ณผ M์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ M ≤ N ≤ 8)

๐Ÿ€ ์ถœ๋ ฅ

ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ๋ฌธ์ œ์˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์ˆ˜์—ด์„ ์ถœ๋ ฅํ•œ๋‹ค. ์ค‘๋ณต๋˜๋Š” ์ˆ˜์—ด์„ ์—ฌ๋Ÿฌ ๋ฒˆ ์ถœ๋ ฅํ•˜๋ฉด ์•ˆ๋˜๋ฉฐ, ๊ฐ ์ˆ˜์—ด์€ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค.

์ˆ˜์—ด์€ ์‚ฌ์ „ ์ˆœ์œผ๋กœ ์ฆ๊ฐ€ํ•˜๋Š” ์ˆœ์„œ๋กœ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค.

๐Ÿ€ ์˜ˆ์ œ

์˜ˆ์ œ ์ž…๋ ฅ 1

3 1

์˜ˆ์ œ ์ถœ๋ ฅ 1

1
2
3

์˜ˆ์ œ ์ž…๋ ฅ 2

4 2

์˜ˆ์ œ ์ถœ๋ ฅ 2

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1

๐Ÿ€ ์„ฑ๊ณต ๊ณผ์ •

์ฒซ ๋ฒˆ์งธ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค.

depth๋ฅผ ํ•˜๋‚˜ ์”ฉ ์ฆ๊ฐ€์‹œํ‚ฌ ๋•Œ, depth+1 ์ด ์•„๋‹Œ depth++๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.
depth++์˜ ๊ฒฝ์šฐ์—๋Š” ์žฌ๊ท€์—์„œ ๋น ์ ธ๋‚˜์˜ค๋”๋ผ๋„ ๊ฐ’์ด ๋‹ค์‹œ ๊ฐ์†Œํ•˜์ง€ ์•Š๋Š”๋‹ค๊ณ ํ•œ๋‹ค.
๋”ฐ๋ผ์„œ depth++์—์„œ depth+1๋กœ ๋ณ€๊ฒฝํ–ˆ๋‹ค.

์ถœ์ฒ˜

๋‘๋ฒˆ์งธ ์‹œ๊ฐ„ ์ดˆ๊ณผ

System.out.println ์„ ์‚ฌ์šฉํ•˜์—ฌ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋‚ฌ๋‹ค.
์‹œ๊ฐ„ ์ดˆ๊ณผ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด StringBuilder๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ–ˆ๋‹ค.

์„ธ ๋ฒˆ์งธ ์„ฑ๊ณต ์ฝ”๋“œ

import java.io.*;
import java.util.*;
public class Main{

    public static boolean[] visited;
    public static Stack<Integer> answer;
    public static StringBuilder sb;

    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        sb = new StringBuilder();

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

        visited = new boolean[n+1];
        answer = new Stack<>();
        calculatePer(0, n, m);

        System.out.println(sb);
    }

    public static void calculatePer(int depth, int n, int m){
        if(m == depth) {
            for (Integer integer : answer) {
                sb.append(integer).append(' ');
            }
            sb.append('\n');
        }

        for(int i = 1; i <= n; i ++){
            if(visited[i]) continue;
            visited[i] = true;
            answer.add(i);
            calculatePer(depth+1, n, m);
            visited[i] = false;
            answer.pop();
        }
    }


}
728x90