[코드 트리] 기울어진 직사각형의 회전 (JAVA)

이형걸·2025년 1월 15일
0

Problem Solving

목록 보기
8/23

[코드 트리] 기울어진 직사각형의 회전 (JAVA)

🗒️알고리즘 분류

#시뮬레이션 #simulation

📌기억해야 할 포인트

이 문제는 이전에 풀었던 문제인 2차원 바람 문제와 유사하다.

한가지 유의해야 하는 점은 직사각형이 행과 열에 평행한 것이 아닌 말 그대로 기울어진 직사각형인 것이다.

그래서 시계방향(ClockWise) 혹은 반시계방향(CounterClockWise)으로 회전할 때, 직사각형의 가로(width),세로(height) 길이를 지정해주고, 해당 길이만큼 한칸 씩 shift 해준다.

  • 시계방향일 때는 int[] length = {1,2,1,2};
  • 반시계방향일 때는 int[] length = {2,1,2,1};

인 것이다.

한칸 씩 옆으로 이동시켜주는 메커니즘은 2차원 바람에서와 똑같이 해주면 된다.

dx, dy 에 시계방향, 반시계방향을 각각 지정해주고, temp 에 시작점의 값을 저장해주고, 반복문 안에서 temp 와 swapTemp 를 이용하여 한칸씩 값을 바꿔주면 된다.

📝풀이 코드(JAVA)

import java.util.*;

public class Main {
    private static int N = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        int[][] arr = new int[n][n];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                arr[i][j] = sc.nextInt();
            }
        }

        int index = 0;
        int[] query = new int[7];
        while (sc.hasNextInt()) { 
            query[index++] = sc.nextInt();
        }

        sc.close();

        rotate(arr, query);

        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
        return;
    }

    private static void rotate(int[][] arr, int[] query) {
        int r = query[0]-1;
        int c = query[1]-1;
        int[] length = new int[4];
        int[] dx;
        int[] dy;
        boolean isClockwise = query[6] == 1;

        if (isClockwise) {
            length[0] = query[5];
            length[1] = query[4];
            length[2] = query[3];
            length[3] = query[2];
            dx = new int[]{-1,-1,1,1};
            dy = new int[]{-1,1,1,-1};
        } else {
            length[0] = query[2];
            length[1] = query[3];
            length[2] = query[4];
            length[3] = query[5];
            dx = new int[]{-1,-1,1,1};
            dy = new int[]{1,-1,-1,1};
        }
        shift(arr, r,c,dx,dy,length);
    }

    private static void shift(int[][] arr, int x, int y, int[] dx, int[] dy, int[] length) {
        int temp = arr[x][y];

        for (int direction = 0; direction < 4; ++direction) {
            for (int step = 0; step < length[direction]; ++step) {
                int nx = x + dx[direction];
                int ny = y + dy[direction];

                int swapTemp = arr[nx][ny];
                arr[nx][ny] = temp;
                temp = swapTemp;

                x = nx;
                y = ny;
            }
        }
    }
}

⏰총 풀이시간

  • 60분
profile
현명하고 성실하게 살자

0개의 댓글