-
[백준] 10026 적록색약 #JAVAAlgorithm Solving/BAEKJOON 2020. 12. 17. 22:19
BAEKJOON [10026] 적록색약
코드
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int mapSize = Integer.parseInt(br.readLine()); char[][] map = new char[mapSize][mapSize]; char[][] mapRB = new char[mapSize][mapSize]; boolean[][] mapVis = new boolean[mapSize][mapSize]; boolean[][] mapVisRB = new boolean[mapSize][mapSize]; int[] dx = {0,1,0,-1}; int[] dy = {1,0,-1,0}; Queue<int[]> queue = new LinkedList<int[]>(); int rgbCnt = 0; int rbCnt = 0; //input map data for (int i = 0; i < mapSize; i++) { char[] input = br.readLine().toCharArray(); for (int j = 0; j < mapSize; j++) { map[i][j] = input[j]; if(input[j] == 'G') { mapRB[i][j] = 'R'; //적록색약 }else { mapRB[i][j] = input[j]; } } } //bfs RGB for (int i = 0; i < mapSize; i++) { for (int j = 0; j < mapSize; j++) { if(!mapVis[i][j]) {//false queue.add(new int[] {i,j}); rgbCnt++; } while (!queue.isEmpty()) { int[] temp = queue.poll(); char target = map[temp[0]][temp[1]]; for (int k = 0; k < 4; k++) { int nx = temp[0]+dx[k]; int ny = temp[1]+dy[k]; if(nx<0 || ny<0 || nx>=mapSize || ny>=mapSize) continue; if(target != map[nx][ny]) continue; //다른 문자이면 if(mapVis[nx][ny]) continue; //이미 방문함 mapVis[nx][ny] = true; queue.add(new int[]{nx,ny}); } } } } queue.clear(); //bfs R(G)B 적록색약 for (int i = 0; i < mapSize; i++) { for (int j = 0; j < mapSize; j++) { if(!mapVisRB[i][j]) {//false queue.add(new int[] {i,j}); rbCnt++; } while (!queue.isEmpty()) { int[] temp = queue.poll(); char target = mapRB[temp[0]][temp[1]]; for (int k = 0; k < 4; k++) { int nx = temp[0]+dx[k]; int ny = temp[1]+dy[k]; if(nx<0 || ny<0 || nx>=mapSize || ny>=mapSize) continue; if(target != mapRB[nx][ny]) continue; //다른 문자이면 if(mapVisRB[nx][ny]) continue; //이미 방문함 mapVisRB[nx][ny] = true; queue.add(new int[]{nx,ny}); } } } } System.out.println(rgbCnt+" "+ rbCnt); } }
풀이
- BFS
- RGB 구분하도록 BFS 1회, 적록색약(RB) 구분하도록 BFS 1회
잘못된 코드나 내용이 있다면 댓글을 남겨주세요. 즉시 수정하도록 하겠습니다! :)
'Algorithm Solving > BAEKJOON' 카테고리의 다른 글
[백준] 9663 N-Queen #JAVA (0) 2021.01.14 [백준] 15649 N과 M (1) #JAVA (0) 2021.01.10 [백준] 7562 나이트의 이동 #JAVA (0) 2020.12.16 [백준] 2667 단지번호 붙이기#JAVA (0) 2020.12.14 [백준] 2583 영역 구하기#JAVA (0) 2020.12.13