알고리즘

프로그래머스 - 덧칠하기

계양 꿀주먹 2024. 4. 29. 11:33

 


 

class Solution {
    public int solution(int n, int m, int[] section) {
        int answer = 0;
        boolean[] wall = new boolean[n];
        
        for(int i = 0; i < section.length; i++) {
            wall[section[i] - 1] = true;
        }
        
        for(int i = 0; i < wall.length; i++) {
            if(wall[i]) {
                answer++;
                for(int j = 0; j < m; j++) {
                    if(i + j < wall.length) wall[i + j] = false;
                }
            }
        }
        
        return answer;
    }
}

 

길이가 n인 벽을 배열로 선언해주고, 새롭게 덧칠을 해야하는 부분을 true로 변경 후, wall 배열을 탐색하여 true인 부분부터 m만큼 색을 다시 덧칠해주고 횟수를 증가시킵니다.

이 때, 배열의 크기를 넘길 수 있으므로 조건을 걸어줍니다.