티스토리 뷰

728x90
 

COS Pro 1급 Java 모의고사 - 꽃피우기

정사각형 크기 격자 모양 정원에 칸마다 핀 꽃 또는 피지 않은 꽃을 심었습니다. 이 정원의 꽃이 모두 피는 데 며칠이 걸리는지 알고 싶습니다. 핀 꽃은 하루가 지나면 앞, 뒤, 양옆 네 방향에 있

programmers.co.kr

// 다음과 같이 import를 사용할 수 있습니다.
import java.util.*;

class Solution {
    static class Dot{
        int x;
        int y;
        int nextDay;
        Dot(int x,int y,int nextDay){
            this.x = x;
            this.y =y;
            this.nextDay =nextDay;
        }
    }
    public int solution(int[][] garden) {
        // 여기에 코드를 작성해주세요.
        int answer = 0;
        int []dx = {1,-1,0,0};
        int []dy = {0,0,-1,1};
        Queue<Dot> q = new LinkedList<>();      
        for(int i=0;i<garden.length;i++){
            for(int j=0;j<garden.length;j++){
                if(garden[i][j]!=0){
                    q.offer(new Dot(i,j,0));
                }
            }
        }
        int len = garden.length;
        while(!q.isEmpty()){
            Dot dot = q.poll();
            for(int i=0;i<4;i++){
                int cx = dot.x +dx[i];
                int cy = dot.y +dy[i];
                int nextDay = dot.nextDay+1;
                if(cx>-1&&cy>-1&&cx<len&&cy<len&&garden[cx][cy]!=1){
                    answer = nextDay;
                    garden[cx][cy]=1;
                    q.offer(new Dot(cx,cy,nextDay));
                }
            }
        }
        
        return answer;
    }
 }

'알고리즘 - Java' 카테고리의 다른 글

[Programmers] 베스트 앨범-Java  (0) 2022.03.20
[Programmers] 영어 끝말잇기-Java  (0) 2022.03.18
[COS Pro 1급] - 메모장(6차)  (0) 2022.03.16
[COS Pro] 1급 - 숫자 뽑기(6차)  (0) 2022.03.16
[백준] 3109 빵집 - Java  (0) 2021.08.19
댓글
최근에 달린 댓글
최근에 올라온 글
Total
Today
Yesterday
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31