Algorithm/BOJ

[BOJ] 배열 돌리기 1

goakgoak 2020. 2. 10. 22:39

[16926] 배열 돌리기 1

https://www.acmicpc.net/problem/16926

  • 배열의 크기(N,M), 회전의 수(R), 배열 정보가 주어졌을 때 배열을 반시계 방형으로 R번 회전시킨 결과를 구하는 문제

 

 

Solution

  • 코테에서 자주 나오는 유형이니 외워두자.
  • 시간 안습

 

 

소스코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.Scanner;
 
public class Main {
    static int n, m, r;
    static int[] dx = { 010-1 };
    static int[] dy = { 10-10 };
    static int[][] arr;
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        r = sc.nextInt();
 
        arr = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j] = sc.nextInt();
            }
        }
 
        int s = Math.min(n, m) / 2;
 
        for (int i = 0; i < r; i++) {
            rotate(s);
        }
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
 
    }
 
    static void rotate(int s) {
 
        for (int i = 0; i < s; i++) {
            int dir = 0;
            int sx = i;
            int sy = i;
            int value = arr[sx][sy];
            while (dir < 4) {
                int nx = sx + dx[dir];
                int ny = sy + dy[dir];
 
                if (nx >= i && ny >= i && nx < n - i && ny < m - i) {
                    arr[sx][sy] = arr[nx][ny];
 
                    sx = nx;
                    sy = ny;
                } else {
                    dir++;
                }
            }
            arr[i + 1][i] = value;
        }
    }
}
cs