본문 바로가기

알고리즘/DFS

[DFS] 1027 : 좋은수열

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 
import java.util.Scanner;
public class GoodSequence {
    public static void main(String[] args) {
        GoodSequence n = new GoodSequence();
        n.goodSequence(0);
        n.display();
    }
    Scanner sc = new Scanner(System.in);
    int deepMax = sc.nextInt();
    StringBuffer sequence = new StringBuffer();
    boolean isFind = false;
    public void goodSequence(int deep){
        if(deep == deepMax){
            isFind = true;
            return;
        }
        for(int i = 1; i <= 3; i++){
            if(isFind) return;
            if(isGood(i, deep+1)){
                goodSequence(deep+1);
            }
        }
        if(isFind) return;
        sequence.deleteCharAt(sequence.length()-1);
        return;
    }
    public boolean isGood(int target, int deep){
        sequence.append(target);
        int length = deep;
        for(int i = length/2; i>0; i--){
            if(sequence.substring(length-i, length).equals(sequence.substring(length-2*i, length-i))){
                sequence.deleteCharAt(sequence.length()-1);
                return false;
            }
        }
        return true;
    }
    public void display(){
        System.out.print(sequence.toString());
    }
}
 
cs


'알고리즘 > DFS' 카테고리의 다른 글

[DFS] Nqueen Algorithm  (0) 2015.04.22