본문 바로가기
코딩테스트/프로그래머스

[JAVA][2025 프로그래머스 코드챌린지 1차 예선] 지게차와 크레인

by coding_whale 2026. 3. 14.
반응형

문제 : [2025 프로그래머스 코드챌린지 1차 예선] 지게차와 크레인

난이도 : level 2

정답률 : 44%

 

 

 

풀이 전략

1. 꺼낸 알파벳은 '.'으로 변환하여 처리

2. 탐색은 해야하는데 재귀는 필요하지 않으므로 bfs라고 생각

3. 탐색은 테두리에서 진행 -> 크기를 +2씩 증가시켜 진행

 

 

 

 

코드

import java.util.*;

class Solution {

    char[][] map;
    int[] dx = {-1,1,0,0};
    int[] dy = {0,0,1,-1};

    public int solution(String[] storage, String[] requests) {

        int n = storage.length;
        int m = storage[0].length();

        map = new char[n+2][m+2];
		
        // .으로 초기화
        for(int i=0;i<n+2;i++)
            Arrays.fill(map[i], '.');
		
        // 알파벳 채우기
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                map[i+1][j+1] = storage[i].charAt(j);
            }
        }
		
        // 2개면 다 제거, 1개면 이어진 알파벳만 제거
        for(String r : requests){

            char c = r.charAt(0);

            if(r.length()==2){
                deleteAll(c);
            }else{
                deleteOne(c);
            }
        }

        int count=0;
		
        
        // 배열 순회하면서 count 세기
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                if(map[i][j]!='.')
                    count++;
            }
        }

        return count;
    }
	
    
    // 다 없애는 경우
    private void deleteAll(char c){

        for(int i=0;i<map.length;i++){
            for(int j=0;j<map[0].length;j++){
                if(map[i][j]==c)
                    map[i][j]='.';
            }
        }
    }
	
    // 하나만 없애는 경우
    private void deleteOne(char c){

        int n = map.length;
        int m = map[0].length;

        boolean[][] visited = new boolean[n][m];

        Queue<int[]> q = new ArrayDeque<>();

        q.add(new int[]{0,0});
        visited[0][0]=true;

        while(!q.isEmpty()){

            int[] cur = q.poll();

            for(int i=0;i<4;i++){

                int nx = cur[0]+dx[i];
                int ny = cur[1]+dy[i];
				
                //예외인 경우
                if(nx<0||ny<0||nx>=n||ny>=m||visited[nx][ny])
                    continue;

                if(map[nx][ny]==c){
                    map[nx][ny]='.';
                }
                else if(map[nx][ny]=='.'){
                    q.add(new int[]{nx,ny});
                }

                visited[nx][ny]=true;
            }
        }
    }
}

 

 

 

느낀점 

테두리를 신경쓰는 부분이 조금 새롭게 다가왔음 배열의 크기를 늘려 진행하는 것이 맞다고 생각하는 데에 좀 걸림

또한 기존 배열 storage를 활용해보려 했으나 String 배열이라 값을 바꾸는게 불가능했음 -> 2차원 배열을 새로 선언해야 했음

반응형