지구 온난화 - 백준(5212, 시뮬레이션)

백마금편·2022년 3월 29일
0

코딩테스트

목록 보기
2/3
post-thumbnail

🎯 RGB 거리

[백준]지구 온난화 - 5212, 시뮬레이션, 실버2


🧐 알고리즘[접근방법]

  1. 현재 지도와 같은 크기의 임시지도 선언(동시에 진행되기 때문에 현재값을 저장해야한다.)
  • 객체를 선언하여 현재값 저장하는 방법도 가능
  1. 지도를 탐색하면서 섬인 부분 중 인접한 지역이 3곳 이상 바다면 임시 지도에 바다로 변경

  2. 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();
  }

}


🏅 결과


📖 관련 지식

profile
뭐 어떻게 잘 되겠지

0개의 댓글