지도를 탐색하면서 섬인 부분 중 인접한 지역이 3곳 이상 바다면 임시 지도에 바다로 변경
50년 후 임시 지도를 탐색하면서 최소로 출력할 범위 구하기
import java.util.*;
public class CommonTest {
public static int R;
public static int C;
public static char [][] map;
public static char [][] tempMap;
public static final int[] dx = {0, 0, 1, -1};
public static final int[] dy = {1, -1, 0, 0};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int R = sc.nextInt();
int C = sc.nextInt();
map = new char[R][C];
tempMap = new char[R][C];
sc.nextLine();
for(int i = 0 ; i < map.length ; i++) {
String s = sc.nextLine();
map[i] = s.toCharArray();
tempMap[i] = s.toCharArray();
}
for(int i = 0 ; i < map.length ; i++) {
for(int j = 0 ; j < map[i].length ; j++) {
if(map[i][j] == 'X') {
int count = 0;
for(int k = 0 ; k < dx.length ; k++) {
int nx = i + dx[k];
int ny = j + dy[k];
if(0 <= nx && nx < R && 0 <= ny && ny < C) {
if(map[nx][ny] == '.') {
count++;
}
}else { // 지도 밖은 바다로 취급
count++;
}
}
if(count >= 3) { // 잠긴 섬
tempMap[i][j] = '.';
}
}
}
}
// 최소한의 출력하기 위한 변수 설정
int minR = Integer.MAX_VALUE;
int maxR = Integer.MIN_VALUE;
int minC = Integer.MAX_VALUE;
int maxC = Integer.MIN_VALUE;
for(int i = 0 ; i < R ; i++) {
for(int j = 0 ; j < C ; j++) {
if(tempMap[i][j] == 'X') {
minR = Math.min(minR, i);
maxR = Math.max(maxR, i);
minC = Math.min(minC, j);
maxC = Math.max(maxC, j);
}
}
}
// 출력
for(int i = minR ; i <= maxR ; i++) {
for(int j = minC ; j <= maxC ; j++) {
System.out.print(tempMap[i][j]);
}
System.out.println();
}
sc.close();
}
}