백준 사탕 게임

KIMYEONGJUN·2025년 2월 20일
post-thumbnail

문제

내가 생각했을때 문제에서 원하는부분

첫째 줄에 보드의 크기 N이 주어진다. (3 ≤ N ≤ 50)
다음 N개 줄에는 보드에 채워져 있는 사탕의 색상이 주어진다. 빨간색은 C, 파란색은 P, 초록색은 Z, 노란색은 Y로 주어진다.
사탕의 색이 다른 인접한 두 칸이 존재하는 입력만 주어진다.

첫째 줄에 상근이가 먹을 수 있는 사탕의 최대 개수를 출력한다.

내가 이 문제를 보고 생각해본 부분

입력 처리: BufferedReader를 사용하여 입력을 받는다.
사탕 교환: 인접한 두 사탕을 교환하고, 최대 사탕 개수를 계산한다.
최대 사탕 개수 계산: 행과 열을 각각 검사하여 최대 연속 사탕 개수를 구한다.
결과 출력: 최대 개수를 출력한다.

코드로 구현

package baekjoon.baekjoon_26;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// 백준 3085번 문제
public class Main938 {
    static int N;
    static char[][] board;
    static int maxCandies = 0;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        board = new char[N][N];

        for (int i = 0; i < N; i++) {
            board[i] = br.readLine().toCharArray();
        }

        // 모든 인접한 두 칸에 대해 교환 시도
        for(int i = 0; i < N; i++) {
            for(int j = 0; j < N; j++) {
                // 오른쪽 교환
                if(j < N - 1) {
                    swapAndCheck(i, j, i, j + 1);
                }
                // 아래쪽 교환
                if(i < N - 1) {
                    swapAndCheck(i, j, i + 1, j);
                }
            }
        }

        // 결과 출력
        System.out.println(maxCandies);
        br.close();
    }

    static void swapAndCheck(int x1, int y1, int x2, int y2) {
        // 사탕 교환
        char temp = board[x1][y1];
        board[x1][y1] = board[x2][y2];
        board[x2][y2] = temp;

        // 최대 사탕 개수 계산
        maxCandies = Math.max(maxCandies, getMaxCandies());

        // 사탕 원래대로 되돌리기
        board[x2][y2] = board[x1][y1];
        board[x1][y1] = temp;
    }

    static int getMaxCandies() {
        int max = 0;

        // 행 체크
        for(int i = 0; i < N; i++) {
            int count = 1;
            for(int j = 1; j < N; j++) {
                if(board[i][j] == board[i][j - 1]) {
                    count++;
                } else {
                    max = Math.max(max, count);
                    count = 1;
                }
            }
            max = Math.max(max, count);
        }

        // 열 체크
        for(int j = 0; j < N; j++) {
            int count = 1;
            for(int i = 1; i < N; i++) {
                if(board[i][j] == board[i - 1][j]) {
                    count++;
                } else {
                    max = Math.max(max, count);
                    count = 1;
                }
            }
            max = Math.max(max, count);
        }

        return max;
    }
}

마무리

코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.

profile
Junior backend developer

0개의 댓글