[๋ฐฑ์ค] 6603 ๋ก๋
https://www.acmicpc.net/problem/6603
๋ฌธ์ ์ ๊ทผ
๋ฐฑํธ๋ํน ๋ฐฉ์์ผ๋ก ์ ๊ทผํ์ฌ ์ฌ๊ทํจ์๋ฅผ ์ด์ฉํ DFS๋ฅผ ์ด์ฉํ์ฌ ํ์๋ค.
๋จผ์ ์
๋ ฅ์ ๋ฐ์ ์ซ์๋ฅผ nums์ ์ ์ฅํ๊ณ ์ฌ์ฉํ๋์ง๋ฅผ ์ ์ฅํ๊ธฐ ์ํด์ nums์ ๊ฐ์ ํฌ๊ธฐ์ boolean ๋ฐฐ์ด๋ก visited๋ฅผ ๋ง๋ค์๋ค.
๊ทธ๋ฆฌ๊ณ ์ต์ข
์ ์ผ๋ก 6๊ฐ์ ๋ก๋ ๋ฒํธ๋ฅผ ์ ์ฅํ๊ธฐ ์ํ ๋ฐฐ์ด lotto๋ฅผ ๋ง๋ค์๋ค.
๊ฒฐ๊ณผ๊ฐ ์ค๋ฆ์ฐจ์์ผ๋ก ๋์์ผ ํด์ lotto[cnt-1]๊ณผ nums[i]๋ฅผ ๋น๊ตํด์ ํ์์ ๊ฑด๋๋ฐ๋๋ก ๋ง๋ค์๋ค.
Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BOJ6603 {
static int[] nums;
static boolean[] visited;
static int[] lotto = new int[6];
static StringBuilder sb;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
String[] input = br.readLine().split(" ");
if(input[0].equals("0")) break;
nums = new int[Integer.parseInt(input[0])];
visited = new boolean[Integer.parseInt(input[0])];
for(int i = 1; i<input.length; i++){
nums[i-1] = Integer.parseInt(input[i]);
}
sb = new StringBuilder();
generateLotto(0);
System.out.println(sb.toString());
}
}
static void generateLotto(int cnt){
if(cnt == 6){
for(int i = 0; i<lotto.length; i++){
sb.append(lotto[i]);
if(i!=lotto.length-1) sb.append(" ");
}
sb.append("\n");
} else {
for(int i = 0; i<nums.length; i++){
if(!visited[i]){
if(cnt != 0 && lotto[cnt-1] > nums[i]) continue;
// ์ซ์๋ฅผ ๋ก๋์ ํฌํจํ์ ๋
visited[i] = true;
lotto[cnt] = nums[i];
generateLotto(cnt+1);
// ์ซ์๋ฅผ ๋ก๋์ ํฌํจํ์ง ์์์ ๋
visited[i] = false;
}
}
}
}
}
๋๋ ์
์ด์ ๋ DFS์ BFS ๊ธฐ๋ณธ ๋ฌธ์ ๋ ์ ํ ์ ์๊ฒ๋ ๊ฒ ๊ฐ๋ค. ๋ค๋ฅธ ๋ธ๋ก๊ทธ ํ์ด๋ฅผ ๋ณด๋๊น ์ค๋ฆ์ฐจ์์ผ๋ก ํ๊ธฐ ์ํด์ generateLottoํจ์์ cnt ํ๋ผ๋ฏธํฐ ๋ง๊ณ ์์ ์ธ๋ฑ์ค๋ฅผ ํ๋ผ๋ฏธํฐ๋ก ๋ฐ์์ ๊ทธ ํ๋ผ๋ฏธํฐ ๋ถํฐ for๋ฌธ์ ๋๋ฆฌ๋ ๋ฐฉ์์ด ์๋๋ฐ ๊ทธ๊ฒ๋ ์ข์๊ฒ ๊ฐ๋ค.
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Algorithm/Java][๋ฐฑ์ค] 9020 ๊ณจ๋๋ฐํ์ ์ถ์ธก (0) | 2022.03.26 |
---|---|
[Algorithm/Java][ํ๋ก๊ทธ๋๋จธ์ค] ๋ ๋ฐ๋จน๊ธฐ (0) | 2022.03.24 |
[Algorithm/Java][ํ๋ก๊ทธ๋๋จธ์ค] ํ๋ฆฐํฐ (0) | 2022.03.05 |
[Algorithm/Java][๋ฐฑ์ค] 14502 ์ฐ๊ตฌ์ (0) | 2022.03.05 |
[Algorithm/Java][ํ๋ก๊ทธ๋๋จธ์ค] ๋ ๋งต๊ฒ (0) | 2022.02.26 |