프로그래머스_바탕화면 정리

권권·2023년 3월 20일
0

Java 예제🛒

목록 보기
9/14
post-thumbnail

프로그래머스_ 바탕화면정리 문제
https://school.programmers.co.kr/learn/courses/30/lessons/161990
드래그 하였을 때, 모든 자료들을 삭제할 수 있는 점들을 구하는 문제이다.
[ 처음행, 처음 열, 마지막행, 마지막열]

접근 방법

  1. '#' 을 찾아주고 그 위치를 반환할 수 있는 식을 세워야함
    (이중 for 문을 통해서 해결 ==> 이중 for 문의 바깥 for 는 행, 안쪽 for는 열)

  2. max와 min 메서드를 통해서 계속 비교해주며 값을 갱신해준다.

  3. 마지막 점은 +1 씩 해줘야 전체가 드래그 된다.

코드

class Solution {
    public int[] solution(String[] wallpaper) {
        int[] answer = {};
        
        // 최소점(x, y)와 최대점(x,y) 를 정의해준다. 
        int min_x;
        int min_y;
        int max_x;
        int max_y;
        
        // 각 값들을 알맞게 초기화
        min_x = min_y = Integer.MAX_VALUE;
        max_x = max_y = Integer.MIN_VALUE;
        
        // # 을 찾아줘야함
        for(int i = 0 ; i < wallpaper.length ; i++){
            for(int j = 0 ; j < wallpaper[0].length() ; j++){
                if(wallpaper[i].charAt(j) == '#'){
                    min_x = Math.min(min_x , i);
                    min_y = Math.min(min_y , j);
                    max_x = Math.max(max_x , i);
                    max_y = Math.max(max_y , j);
                }
            }
        }
        // max 점 들에는 +1 씩 해줘야 모두 지워짐 
       return new int[] {min_x, min_y, max_x+1, max_y+1};
    }
}
profile
안녕하세요

0개의 댓글