취미처럼

[백준] 10974번 모든 순열 본문

Algorithm/백준

[백준] 10974번 모든 순열

sirius 2021. 3. 4. 17:25

https://www.acmicpc.net/problem/10974

 

10974번: 모든 순열

N이 주어졌을 때, 1부터 N까지의 수로 이루어진 순열을 사전순으로 출력하는 프로그램을 작성하시오.

www.acmicpc.net

 

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

public class Main {

    public static int N;
    public static int[] arr;
    public static boolean[] visit;
    public static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) throws Exception {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        arr = new int[N];
        visit = new boolean[N];

        dfs(0);
        System.out.println(sb);
    }  

    public static void dfs(int depth) {
        if(depth == N) {
            for(int i= 0; i < N; i++) { 
            	sb.append(arr[i]).append(" ");
            }
            sb.append("\n");
            return;
        }

        for(int i = 0 ; i < N ; i ++ ) {
            if(!visit[i]) {
                visit[i] = true;
                arr[depth] = i + 1; 
                dfs(depth + 1);
                visit[i] = false;
            }
        }
    }
}

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

[백준] 10971번 외판원 순회 2  (0) 2021.03.04
[백준] 10819번 차이를 최대로  (0) 2021.03.04
[백준] 10973번 이전 순열  (0) 2021.03.04
[백준] 10972번 다음 순열  (0) 2021.03.04
[백준] 2529번 부등호  (0) 2021.03.04
Comments