๋ฐ์ํ
https://www.acmicpc.net/problem/15649
์ฝ๋
import java.util.Scanner;
public class Main {
static int arr[];
static boolean visit[];
static int N;
static int M;
static StringBuilder sb = new StringBuilder();
public static void dfs(int count) {
// dfs ํจ์ ํ์ถ - ๋ฝ์ ๊ฐฏ์์ M์ด ๋์ผํ ๋
if(count == M) {
// StringBuilder ์ ๋ฝ์ ๊ฐ(arr) ์ ์ฅ
for(int i : arr)
sb.append(i + " ");
sb.append("\n");
return;
}
// ๋ฝ์ง์์๊ฒ -> dfs ์ฌ๊ทํธ์ถ
for(int i=1; i<=N; i++) {
if(!visit[i]) {
visit[i] = true; // ๋ฐฉ๋ฌธ ์ฒดํฌ
arr[count] = i; // ๋ฝ๊ธฐ
dfs(count+1); // ๊ทธ ๋ค์ ๊ฐ ๋ฝ๊ธฐ์ํด ์ฌ๊ทํธ์ถ
visit[i] = false; // ๋ฝ์ ๋ค ๋ฏธ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
N = scan.nextInt();
M = scan.nextInt();
arr = new int[M];
visit = new boolean[N+1];
dfs(0);
System.out.print(sb);
scan.close();
}
}
ํ์ด
์์ด๊ณผ ์กฐํฉ์ ์ฒซ๋ฒ์งธ๋ฌธ์ ,
dfs๋ฅผ ํตํด ๊น์ํ ๋ฐฉ๋ฌธํ์ง ์์ ๊ณณ์ ๋ฝ๊ณ , ๋ฝ์๊ฐฏ์๊ฐ M๊ณผ ๋์ผํ ๋(dfs ํ์ถ)
StringBuilder ์ ๋ฃ์ด์ค๋ค.
๋ฐ์ํ
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Codeforces] 1154A - Restoring Three Numbers (0) | 2020.02.19 |
---|---|
[๋ฐฑ์ค] 15650๋ฒ: N๊ณผ M (2) (dfs, ๋ฐฑํธ๋ํน) (0) | 2020.02.18 |
[๋ฐฑ์ค] 6986๋ฒ: ์ ์ฌํ๊ท (0) | 2020.02.14 |
[Codeforces] 791A: Bear and Big Brother (0) | 2020.02.13 |
[๋ฐฑ์ค] 1931๋ฒ: ํ์์ค๋ฐฐ์ (๊ทธ๋ฆฌ๋, ์ ๋ ฌ) (0) | 2020.02.12 |
๋๊ธ