[백준] 15649 N과 M(1)

알파·2022년 7월 1일
0

Algorithm

목록 보기
18/20

백트래킹

  • 어떤 노드의 유망성을 판단한 뒤 해당 노드가 유망하지 않다면 부모 노드로 돌아가 다른 자식노드를 찾는 알고리즘이다.
  • DFS로 풀이할 수 있다. (깊이 우선으로 탐색하다가 해당 노드가 유망하지 않을 경우 탐색 중지)
  • 노드의 유망성을 판단하기 위한 조건을 잘 설정하는 것이 중요하다

풀이

arr에 depth에 맞는 값을 담아서 dfs가 depth만큼 돌면 arr를 출력하면 된다.

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

public class Solution15649 {
    static int N, M;
    static int[] arr;
    static boolean[] visited;
    public static void main(String[] args) throws IOException {
//4 2
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        arr = new int[M];
        visited = new boolean[N+1];

        dfs(0);
    }

    static void dfs(int depth) {
        if(depth == M) {
            for(int a : arr) {
                System.out.print(a + " ");
            }
            System.out.println();
            return;
        }

        for(int i = 1; i < N+1; i++) {
            if(!visited[i]) {
                visited[i] = true;
                arr[depth] = i;
                dfs(depth+1);
                visited[i] = false;
            }
        }
    }
}
profile
I am what I repeatedly do

0개의 댓글