알고리즘

[프로그래머스] 정수를 나선형으로 배치하기 JAVA 풀이

sppl24 2024. 10. 2. 15:34
반응형

정수를 나선형으로 배치하기

문제 설명

양의 정수 n이 매개변수로 주어집니다. n × n 배열에 1부터 n^2 까지 정수를 인덱스 [0][0]부터 시계방향 나선형으로 배치한 이차원 배열을 return 하는 solution 함수를 작성해 주세요.


제한사항

  • 1 <= n <= 30

입출력 예

입출력 예


아이디어

  • 방향을 분류(상하좌우) 한다.
  • 분류한 방향의 다음에 값이 있는지 체크, 방향 전환 처리 주의

풀이

class Solution {
    public int[][] solution(int n) {
        int[][] answer = new int[n][n];
        int col = 0;
        int row = 0;

        // 방향 - e: 우, s: 하, w: 좌, n: 상
        String direction = "e";
        for (int i = 1; i <= n * n; i++) {
            answer[row][col] = i;
            if (direction.equals("e")) {
                if (col == n - 1 || answer[row][col + 1] != 0) {
                    direction = "s";
                    row++;
                } else {
                    col++;
                }
            } else if (direction.equals("s")) {
                if (row == n - 1 || answer[row + 1][col] != 0) {
                    direction = "w";
                    col--;
                } else {
                    row++;
                }
            } else if (direction.equals("w")) {
                if (col == 0 || answer[row][col - 1] != 0) {
                    direction = "n";
                    row--;
                } else {
                    col--;
                }
            } else if (direction.equals("n")) {
                if (row == 0 || answer[row - 1][col] != 0) {
                    direction = "e";
                    col++;
                } else {
                    row--;
                }
            }
        }
        return answer;
    }
}
반응형