문제/백준

백준 3085번 사탕 게임 [JAVA]

javaju 2021. 11. 18. 02:04
 

3085번: 사탕 게임

예제 3의 경우 4번 행의 Y와 C를 바꾸면 사탕 네 개를 먹을 수 있다.

www.acmicpc.net

 

풀이 방법

배열 전체를 돌면서 기준이 되는 사탕과 인접한 사탕의 색깔이 다른 경우 위치를 교환해, 행과 열을 확인하여 최대 먹을 수 있는 사탕을 계산해 주었습니다.

 

 

코드

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Main_BJ_3085_사탕게임 {
    
    static int [] dx = {-1,0,1,0};
    static int [] dy = {0,1,0,-1};
    
    static int N, max=0;
    static char [][] map;
    
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        N = Integer.parseInt(br.readLine());
        
        map = new char[N][N];
        
        for(int i=0;i<N;i++) {
            String line = br.readLine();
            for(int j=0;j<N;j++) {
                map[i][j] = line.charAt(j);
            }
        }
        
        candy();
        System.out.println(max);
    }
    
    public static void candy() {
        for(int x=0;x<N;x++) {
            for(int y=0;y<N;y++) {
                
                for(int d=0;d<4;d++) { // 상 하 좌 우 인접한곳
                    int nx = x + dx[d];
                    int ny = y + dy[d];
                    
                    if(range(nx,ny) && map[x][y]!=map[nx][ny]) {
                        char temp = map[x][y];
                        map[x][y] = map[nx][ny];
                        map[nx][ny] = temp;
                        
                        check(); //먹을 수 있는 사탕 개수 확인
                        
                        temp = map[x][y];
                        map[x][y] = map[nx][ny];
                        map[nx][ny] = temp;
                    }
                }
            }
        }
    }
    
    public static boolean range(int x, int y) {
        return x>=0 && x<&& y>=0 && y<N;
    }
    
    public static void check() {
        
        for(int i=0;i<N;i++) {
            for(int j=0;j<N;j++) {
                count(i,j);
            }
        }    
    }
    
    public static void count(int x, int y) {
        
        int yy=y, xx=x, row=1, col=1;
        //연속된 행
        for(int i=y+1;i<N;i++) {
            if(map[x][yy]==map[x][i]) {
                row++;
                yy = i; 
            }else break;
        }
        
        //연속된 
        for(int i=x+1;i<N;i++) {
            if(map[xx][y]==map[i][y]) {
                col++;
                xx = i;
            }else break;
        }
        
        int result = Math.max(row, col);
        max = Math.max(result, max);
    }
 
}
cs