프로그래머스 연습문제 바탕화면 정리 [JAVA] - 23년 3월 7일

Denia·2023년 3월 7일
0

코딩테스트 준비

목록 보기
164/201

처음에 문제를 봤을때 파일이 묶여있는 것 끼리 따로 처리해야 하는 줄 알고 DFS를 사용해서 풀이를 진행했는데 다른 사람들의 풀이를 보니 그냥 모든 좌표를 한번씩만 살펴봐도 풀 수 있는 문제였다. => 문제를 잘 읽어보자.

1차 풀이


class Solution {
    int gRow, gCol;
    int minRow, minCol;
    int maxRow, maxCol;
    char[][] gWallpaper;
    int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    public int[] solution(String[] wallpaper) {
        minRow = minCol = Integer.MAX_VALUE;
        maxRow = maxCol = Integer.MIN_VALUE;

        gRow = wallpaper.length;
        gCol = wallpaper[0].length();
        gWallpaper = new char[gRow][gCol];

        int idx = 0;
        for (String str : wallpaper) {
            gWallpaper[idx] = str.toCharArray();
            idx++;
        }

        for (int r = 0; r < gRow; r++) {
            for (int c = 0; c < gCol; c++) {
                if (wallpaper[r].charAt(c) == '#') {
                    dfs(r, c);
                }
            }
        }

        //max 값에 + 1을 하는 이유는 드래그를 하려면 끝점을 선택해야 함
        return new int[]{minRow, minCol, maxRow + 1, maxCol + 1};
    }

    private void dfs(int r, int c) {
        if (r < minRow) {
            minRow = r;
        }
        if (r > maxRow) {
            maxRow = r;
        }
        if (c < minCol) {
            minCol = c;
        }
        if (c > maxCol) {
            maxCol = c;
        }

        gWallpaper[r][c] = '!';

        for (int[] direction : directions) {
            int newR = r + direction[0];
            int newC = c + direction[1];

            if (newR < 0 || newR >= gRow || newC < 0 || newC >= gCol || gWallpaper[newR][newC] != '#')
                continue;

            dfs(newR, newC);
        }
    }
}

2차 풀이 - 다른 사람 정답 참고


class Solution {
    public int[] solution(String[] wallpaper) {
        int minRow, minCol;
        int maxRow, maxCol;
        
        minRow = minCol = Integer.MAX_VALUE;
        maxRow = maxCol = Integer.MIN_VALUE;

        int row = wallpaper.length;
        int col = wallpaper[0].length();

        for (int r = 0; r < row; r++) {
            for (int c = 0; c < col; c++) {
                if (wallpaper[r].charAt(c) == '#') {
                    minRow = Math.min(minRow, r);
                    minCol = Math.min(minCol, c);
                    maxRow = Math.max(maxRow, r);
                    maxCol = Math.max(maxCol, c);
                }
            }
        }

        //max 값에 + 1을 하는 이유는 드래그를 하려면 끝점을 선택해야 함
        return new int[]{minRow, minCol, maxRow + 1, maxCol + 1};
    }
}

profile
HW -> FW -> Web

0개의 댓글