본문 바로가기

알고리즘/BOJ

[C++] 백준 3085번 - 사탕 게임


0. 문제

 

https://www.acmicpc.net/problem/3085

1. 아이디어

 

1) 2차원 배열을 직접 구현할 수도 있지만 string이 1차원 배열처럼 다룰 수 있다는 사실을 이용한다.

 

2. 소스코드

 

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
#include <iostream>
#include <algorithm>
const int MAX = 50;
int N;
std::string board[MAX];
 
int ReadBoard() // 보드내에서 먹을 수 있는 사탕의 최대 개수 구하기
{
    int result = 1;
    for (int i = 0; i < N; i++)
    {
        int temp = 1;
        for (int j = 1; j < N; j++)
            if (board[i][j - 1== board[i][j]) temp++;
            else
            {
                result = std::max(result, temp);
                temp = 1;
            }
        result = std::max(result, temp);
    }
    for (int i = 0; i < N; i++)
    {
        int temp = 1;
        for (int j = 0; j < N - 1; j++)
            if (board[j + 1][i] == board[j][i]) temp++;
            else
            {
                result = std::max(result, temp);
                temp = 1;
            }
        result = std::max(result, temp);
    }
    return result;
}
 
int main()
{
    std::ios_base::sync_with_stdio(0);
    std::cin.tie(0);
    std::cin >> N;
    for (int i = 0; i < N; i++)
        std::cin >> board[i];
    int result = 1;
 
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N - 1; j++)
        {
            //양 옆
            std::swap(board[i][j], board[i][j + 1]);
            result = std::max(result, ReadBoard());
            std::swap(board[i][j], board[i][j + 1]);
            //위 아래 
            std::swap(board[j][i], board[j + 1][i]);
            result = std::max(result, ReadBoard());
            std::swap(board[j][i], board[j + 1][i]);
        }
    std::cout << result;
}
 
cs

 

3. 결과

 

4. 피드백

 

  • 2차원 배열을 직접 구현하려다 보니까 구현하는데 애먹었다.. string을 1차원 배열로 볼 수 있다는 걸 생각하자.
  • c++내부에 swap() 함수도 이미 구현되어있구나,, 몰랐다.

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

[C++] 백준 2503번 - 숫자야구  (0) 2020.03.04
[C++] 백준 10448번 - 유레카 이론  (0) 2020.03.01
[C++] 백준 2231번 - 분해합  (0) 2020.02.29
[C++] 백준 2309번 - 일곱 난쟁이  (0) 2020.02.29
[C++] 백준 10866번 - 덱  (0) 2020.02.29