빛의 경로 사이클

LJM·2023년 8월 23일
0

programmers

목록 보기
74/92

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

이런 문제는 구현도 오래걸리고 디버깅도 너무 오래걸린다 하...
GPT에게 물어보고 풀었다...

import java.util.*;

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

    public static List<Integer> solution(String[] grid) {
        int n = grid.length;
        int m = grid[0].length();
        boolean[][][] visited = new boolean[n][m][4];
        List<Integer> result = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                for (int d = 0; d < 4; d++) {
                    if (!visited[i][j][d]) {
                        int cycleLength = findCycle(i, j, d, grid, visited);
                        if (cycleLength > 0) {
                            result.add(cycleLength);
                        }
                    }
                }
            }
        }

        Collections.sort(result);
        return result;
    }

    private static int findCycle(int x, int y, int d, String[] grid, boolean[][][] visited) {
        int n = grid.length;
        int m = grid[0].length();
        int start_x = x, start_y = y, start_d = d;
        int count = 0;

        while (true) {
            char direction = grid[x].charAt(y);
            if (direction == 'L') {
                d = (d + 3) % 4;
            } else if (direction == 'R') {
                d = (d + 1) % 4;
            }

            x = (x + dx[d] + n) % n;
            y = (y + dy[d] + m) % m;
            count++;

            if (x == start_x && y == start_y && d == start_d) {
                return count;
            }

            if (visited[x][y][d]) {
                return 0;
            }

            visited[x][y][d] = true;
        }
    }
}
profile
게임개발자 백엔드개발자

0개의 댓글