백준 3085번 사탕게임 JAVA 풀이

Do Hyun ·2025년 6월 8일

BOJ

목록 보기
1/5

다시 풀게된 문제 🎯

BOJ 3085 | 사탕 게임 🍬

  • 문제 번호: 3085
  • 푼 날짜: 2025-06-08

📌 문제 요약

N×N 보드에 다양한 색 사탕이 있고,
인접한 사탕을 한 번 교환할 수 있다.
이때 가장 긴 연속 같은 색 사탕 길이를 구하는 문제.


💡 접근 아이디어

  1. 보드의 모든 칸 (i,j)에 대해
  2. 우측 (i,j+1) 또는 아래 (i+1,j)와 교환
  3. 교환 후 현재 보드에서 calculateMaxCandies() 호출 → 최대 연속 길이 계산
  4. 원상복구
  5. 최댓값 갱신

calculateMaxCandies()는 다음과 같이 구현:

  • 각 행과 각 열에 대해
    • 인접 같은 컬러면 count++, 다른 컬러면 최대값 갱신count = 1 재설정

🛠️ Java 구현

package BaekJoon.basic;

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

public class Q3085 {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        int maxLen = 0;

        int N = Integer.parseInt(br.readLine());

        char[][] 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){
                    swap(board,i,j,i,j+1);
                    maxLen=Math.max(maxLen,calculateMaxLength(board,N));
                    swap(board,i,j,i,j+1);
                }

                if(i < N-1){
                    swap(board,i,j, i+1,j);
                    maxLen = Math.max(maxLen,calculateMaxLength(board,N));
                    swap(board,i,j,i+1,j);
                }

            }
        }

        System.out.println(maxLen);
        
    }

    public static void swap(char[][] board, int x1, int y1 , int x2, int y2){
        char temp = board[x1][y1];
        board[x1][y1] = board[x2][y2];
        board[x2][y2] = temp;
    }

    public static int calculateMaxLength (char[][] board, int N) {
        int maxLen = 0;

        for(int i=0; i< N ; i++){
            int countRow = 1;
            int countCol = 1;

            for(int j=1; j<N; j++) {
                if (board[i][j] == board[i][j - 1]) {
                    countRow++;
                } else {
                    maxLen = Math.max(maxLen, countRow);
                    countRow = 1;
                }

                if (board[j][i] == board[j - 1][i]) {
                    countCol++;
                } else {
                    maxLen = Math.max(countCol, maxLen);
                    countCol = 1;
                }
            }

            maxLen= Math.max(maxLen,countRow);
            maxLen = Math.max(maxLen,countCol);
        }

        return maxLen

    }
}

스스로 피드백 해보기

> 구현력이 아직 매우 부족하다.

> 문제를 제대로 읽지않는다.

> 정의 내리는것을 귀찮아하지말아라.

profile
우당탕탕

0개의 댓글