백준 3085번 사탕 게임

김두현·2023년 1월 8일
1

백준

목록 보기
58/133
post-thumbnail

🔒[문제 url]

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


🪄전체 코드

#include <iostream>
#include <algorithm>
using namespace std;

int n;
char map[51][51];

void INPUT()
{
    //ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cin >> n;
    for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
            scanf("%1s", &map[i][j]);
}

int candy()
{// 현재 map에서 먹을 수 있는 사탕의 최대 갯수를 반환한다.
    int score = 1;

    for(int i = 0; i < n; i++)
    {
        int temp = 1;
        // check row
        for(int j = 1; j < n; j++)
        {
            if(map[i][j] == map[i][j - 1])
            {// 같은 색이 연달아 있다면 1 증가
                score = max(score, temp + 1);
                temp++;
            }
            // 색이 다르다면 1로 초기화
            else temp = 1;
        }

        // check col
        temp = 1;
        for(int j = 1; j < n; j++)
        {
            if(map[j][i] == map[j - 1][i])
            {
                score = max(score, temp + 1);
                temp++;
            }
            else temp = 1;
        }
    }
    return score;
}

void SOLVE()
{
    int ans = 0;

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {// map 위의 각 사탕을 순회하며, 바꿀 수 있다면 바꾼 후 먹을 수 있는 사탕의 갯수를 확인한다.
            char temp;
            // swap row
            if(j < n - 1)
            {
                temp = map[i][j];
                map[i][j] = map[i][j + 1];
                map[i][j + 1] = temp;

                ans = max(ans, candy());

                // BackTracking
                temp = map[i][j + 1];
                map[i][j + 1] = map[i][j];
                map[i][j] = temp;
            }
            // swap col
            if(i < n - 1)
            {
                temp = map[i][j];
                map[i][j] = map[i + 1][j];
                map[i + 1][j] = temp;

                ans = max(ans, candy());

                temp = map[i + 1][j];
                map[i + 1][j] = map[i][j];
                map[i][j] = temp;
            }
        }
    }

    cout << ans;
}

int main()
{
    INPUT();
    SOLVE();
}

🥇문제 후기

GOLD5 미만 난이도는 알고리즘 및 풀이 설명을 주석으로 대체합니다.
주석을 참고해주세요.


💕오류 지적 및 피드백은 언제든 환영입니다. 복제시 출처 남겨주세요!💕
💕좋아요와 댓글은 큰 힘이 됩니다.💕
profile
I AM WHO I AM

0개의 댓글