https://www.acmicpc.net/problem/2630
2630번: 색종이 만들기
첫째 줄에는 전체 종이의 한 변의 길이 N이 주어져 있다. N은 2, 4, 8, 16, 32, 64, 128 중 하나이다. 색종이의 각 가로줄의 정사각형칸들의 색이 윗줄부터 차례로 둘째 줄부터 마지막 줄까지 주어진다.
www.acmicpc.net
저는 해당 문제를 재귀를 이용하여 문제를 해결하였습니다.
재귀를 이용해 시작점과 해당 길이 만큼 color가 같은지를 확인하고 이를 결과에 반영하였습니다.
길이가 1이라면 바로 결과에 반영하고 끝냈습니다.
package BOJ.Recursion;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_2630 {
private static void detectArea(int length, int y, int x, int[][]map,int[] result){
if(length == 1){
int color = map[y][x];
result[color]++;
return ;
}
if(checkAllSameColor(length, y, x, map)){
int color = map[y][x];
result[color]++;
return ;
}
int divide = length / 2;
for(int i = 0 ; i < 2 ; i++){
for(int j = 0 ; j < 2 ; j++){
detectArea(divide, y + divide * i, x + divide * j, map, result);
}
}
}
private static boolean checkAllSameColor(int length, int y, int x, int[][] map) {
int color = map[y][x];
for(int i = y ; i < y + length ; i++){
for(int j = x; j < x + length ; j++){
if(map[i][j] != color){
return false;
}
}
}
return true;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine()," ");
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(st.nextToken());
int[][] map = new int[n][n];
for(int i = 0 ; i < n; i++){
st = new StringTokenizer(br.readLine()," ");
for(int j = 0 ; j < n; j++){
map[i][j] = stoi.apply(st.nextToken());
}
}
int[] result = new int[] {0,0};
detectArea(n,0,0,map,result);
System.out.println(result[0]);
System.out.println(result[1]);
}
}
'알고리즘' 카테고리의 다른 글
백준 2303번 극장 좌석 (JAVA) (0) | 2022.03.04 |
---|---|
백준 2638번 치즈 (JAVA) (0) | 2022.03.03 |
백준 연구소3 (JAVA) (0) | 2022.03.01 |
백준 13905번 세부 (JAVA) (0) | 2022.02.28 |
백준 4673번 셀프 넘버(JAVA) (0) | 2022.02.27 |