Algorithm/Programmers Java

Java 프로그래머스 카카오프렌즈 컬러링북

제우제우 2024. 2. 28. 22:29

https://school.programmers.co.kr/learn/courses/30/lessons/1829

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 분류 : 코딩테스트 연습 > 2017 카카오코드 예선 > 카카오프렌즈 컬러링북

난이도 : 2

 

정답 코드 

import java.util.*;
class Solution {
    
    static class node{
        int x; int y;
        public node(int x, int y){
            this.x = x; this.y = y;
        }
    }
    static int [] arx = {-1,1,0,0};
    static int [] ary = {0,0,-1,1};
    
    public int[] solution(int m, int n, int[][] picture) {
        int [] answer = new int [2];
        ArrayList<Integer> list = new ArrayList<>();
        boolean [][] visited = new boolean [m][n];
        Queue<node> q = new LinkedList<>();
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(!visited[i][j] && picture[i][j] != 0){
                    int count = 1;
                    visited[i][j] = true;
                    long color = picture[i][j];
                    q.add(new node(i, j));
                    while(!q.isEmpty()){
                        node node = q.poll();
                        for(int k = 0; k < 4; k++){
                            int nx = node.x + arx[k];
                            int ny = node.y + ary[k];
                            if(0 <= nx && 0 <= ny && nx < m && ny < n){
                                if(!visited[nx][ny] && picture[nx][ny] == color){
                                    visited[nx][ny] = true;
                                    count++;
                                    q.add(new node(nx, ny));
                                }
                            }
                        }
                    }
                    list.add(count);
                }
            }
        }
        answer[0] = list.size();
        answer[1] = Collections.max(list);
        return answer;
    }
}