https://school.programmers.co.kr/learn/courses/30/lessons/86052

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제는 Lv2 난이도를 가지고 있으며, 3차원 배열을 사용해서 이전 방문했던 이력이 있으면 skip 하고, 그렇지 않으면 사이클 탐색을 시작하면서 사이클을 도는데 몇번이 소요되는지 체크 후 이를 리턴하는 단순한 예제입니다.

 

문제 풀면서 유의사항으로는 answerList 에 오름차순을 적용한 다음에 리턴해야 된다는 점이 있습니다.

 

예제 코드는 아래와 같습니다.

import java.io.IOException;
import java.util.*;

class Solution {
    public static int dx[] = {1,0,-1,0};
    public static int dy[] = {0,1,0,-1};

    public static boolean check[][][];
    public static int row, col;

    public static int[] solution(String[] grid) {
        List<Integer> answerList = new ArrayList<>();
        row = grid.length;
        col = grid[0].length();
        check = new boolean[row][col][4];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                for (int d = 0; d < 4; d++) {
                    if (!check[i][j][d]) {
                        answerList.add(light(grid,i,j,d));
                    }
                }
            }
        }
        // 오름차순 정렬
        answerList.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });
        return answerList.stream().mapToInt(i -> i).toArray();
    }

    // 탐색
    public static int light(String grid[], int r, int c, int d) {
        int count = 0;
        while (true) {
            // 시작점으로 돌아와서 동일한 방향으로 탐색하고자 하는 경우, break
            if (check[r][c][d])
                break;

            count++;
            check[r][c][d] = true;
            if (grid[r].charAt(c) == 'L')
                d = d-1 < 0 ? 3 : d-1;
            if (grid[r].charAt(c) == 'R')
                d = d+1 >= 4 ? 0 : d+1;
            r = (r + dy[d] + row) % row;
            c = (c + dx[d] + col) % col;
        }
        return count;
    }

}

 

+ Recent posts