Baekjoon Algorithm | Problem 15651: N and M (3)
Source
https://www.acmicpc.net/problem/15651
Problem
Solve Baekjoon Online Judge problem 15651, N and M (3).
Input
Follow the input format and constraints given in the original problem statement.
Output
Print the answer required by the problem.
Sample Input 1
3 1
Sample Output 1
1 2 3
Sample Input 2
4 2
Sample Output 2
1 1 1 2 1 3 1 4 2 1 2 2 2 3 2 4 3 1 3 2 3 3 3 4 4 1 4 2 4 3 4 4
Sample Input 3
3 3
Sample Output 3
1 1 1 1 1 2 1 1 3 1 2 1 1 2 2 1 2 3 1 3 1 1 3 2 1 3 3 2 1 1 2 1 2 2 1 3 2 2 1 2 2 2 2 2 3 2 3 1 2 3 2 2 3 3 3 1 1 3 1 2 3 1 3 3 2 1 3 2 2 3 2 3 3 3 1 3 3 2 3 3 3
Algorithm Classification
- Backtracking
Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static StringBuilder sb = new StringBuilder();
static int n, m;
static boolean[] visit;
static int[] arr;
public static void main(String[] args) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
StringTokenizer input = new StringTokenizer(br.readLine(), " ");
n = Integer.parseInt(input.nextToken());
m = Integer.parseInt(input.nextToken());
}
visit = new boolean[n];
arr = new int[m];
dfs(0);
System.out.println(sb);
}
/**
* Depth-first search (DFS)
*/
static void dfs(int depth) {
if (depth == m) {
for (int value : arr) {
sb.append(value).append(" ");
}
sb.append("\n");
return;
}
for (int i = 0; i < n; i++) {
arr[depth] = i + 1;
dfs(depth + 1);
}
}
}