코딩공작소

[프로그래머스]카카오예선_BFS 본문

알고리즘/그래프

[프로그래머스]카카오예선_BFS

안잡아모찌 2021. 4. 20. 22:08

programmers.co.kr/learn/courses/30/lessons/1829

 

코딩테스트 연습 - 카카오프렌즈 컬러링북

6 4 [[1, 1, 1, 0], [1, 2, 2, 0], [1, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 3], [0, 0, 0, 3]] [4, 5]

programmers.co.kr

 

영역의 갯수 구하기 + 영역의 넓이 구하기 문제

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.LinkedList;
import java.util.Queue;
import java.awt.Point;
 
class Solution {
    int []dx = {-1,1,0,0};
    int []dy = {0,0,-1,1};
    
    public int[] solution(int m, int n, int[][] picture) {
        int numberOfArea = 0;
        int maxSizeOfOneArea = 0;
        boolean [][]isV = new boolean[m][n];
        Queue<Point> q = new LinkedList<>();
        
        for(int y=0;y<m;y++){
            for(int x=0;x<n;x++){
                if(picture[y][x] != 0 && !isV[y][x]){
                    //0이 아니면 BFS 시작
                    int value = picture[y][x];
                    int cnt = 1//넓이
                    isV[y][x] = true;
                    numberOfArea++//영역 갯수
                    q.add(new Point(x,y));
                    
                    while(!q.isEmpty()){
                        Point p = q.poll();
                        int tmpX = p.x;
                        int tmpY = p.y;
                        
                        for(int i=0;i<4;i++){
                            int nx = tmpX + dx[i];
                            int ny = tmpY + dy[i];
                            
                            if(nx <0 || nx >= n || ny <0 || ny >= m || isV[ny][nx] || picture[ny][nx] != value) continue;
                            q.add(new Point(nx,ny));
                            isV[ny][nx]=true;
                            cnt++;
                        }
                    }
                    maxSizeOfOneArea = cnt >= maxSizeOfOneArea ? cnt : maxSizeOfOneArea;
                }
            }
        }
        int[] answer = new int[2];
        answer[0= numberOfArea;
        answer[1= maxSizeOfOneArea;
        return answer;
    }
}
cs

'알고리즘 > 그래프' 카테고리의 다른 글

[프로그래머스] PCCP 기출문제 2번 / 석유 시추  (0) 2023.11.27
[프로그래머스] 리코쳇 로봇  (0) 2023.11.16
BackTracking  (0) 2021.04.20
[프로그래머스]여행경로  (0) 2019.10.27
[프로그래머스]단어변환  (0) 2019.10.26