🔗카카오 프렌즈 컬러링북
import java.util.*;
class Solution {
public int[] solution(int m, int n, int[][] picture) {
// 방문 체크 배열
boolean[][] visited = new boolean[m][n];
int[] result = new int[2]; // 결과 저장 [영역 수, 최대 영역 크기]
// 모든 좌표 탐색
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// 방문하지 않은 색칠된 칸이면 BFS 실행
if (!visited[i][j] && picture[i][j] != 0) {
bfs(i, j, m, n, picture, visited, result);
}
}
}
// 결과 반환
return result;
}
private void bfs(int cx, int cy, int m, int n, int[][] picture, boolean[][] visited, int[] result) {
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{cx, cy});
visited[cx][cy] = true;
int[] dx = {1, -1, 0, 0};
int[] dy = {0, 0, 1, -1};
int color = picture[cx][cy];
int areaSize = 0;
while (!queue.isEmpty()) {
int[] c = queue.poll();
int curx = c[0];
int cury = c[1];
areaSize++;// 영역 크기 ++
for (int i = 0; i < 4; i++) {
int nx = curx + dx[i];
int ny = cury + dy[i];
if (nx >= 0 && nx < m && ny >= 0 && ny < n &&
!visited[nx][ny] && picture[nx][ny] == color) {
// 범위 안에 있고 방문하지 않았고 색이 같다면
visited[nx][ny] = true;// 방문한다
queue.offer(new int[]{nx, ny});
}
}
}
result[0]++; // 영역 개수
result[1] = Math.max(result[1], areaSize);// 가장 큰 영역의 개수
}
}