백준 - 16926 - 배열 돌리기1

2021. 4. 7. 15:30Algorithm

www.acmicpc.net/problem/16926

 

16926번: 배열 돌리기 1

크기가 N×M인 배열이 있을 때, 배열을 돌려보려고 한다. 배열은 다음과 같이 반시계 방향으로 돌려야 한다. A[1][1] ← A[1][2] ← A[1][3] ← A[1][4] ← A[1][5] ↓ ↑ A[2][1] A[2][2] ← A[2][3] ← A[2][4] A[2][5]

www.acmicpc.net

 

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
import java.util.Scanner;
 
public class 배열_돌리기1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] inputs = sc.nextLine().split(" ");
        int N = Integer.parseInt(inputs[0]);
        int M = Integer.parseInt(inputs[1]);
        int R = Integer.parseInt(inputs[2]);
        String[][] map = new String[N][M];
 
        for(int i=0; i<N; i++) {
            map[i] = sc.nextLine().split(" ");
        }
 
        int groupCount = Math.min(N, M) / 2;
        int[][] directions = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};//오른쪽, 아래쪽, 왼쪽, 위쪽
        for(int i=0; i<R; i++) {
            for(int j=0; j<groupCount; j++) {
                int x = j;
                int y = j;
 
                int directionIndex = 0;
                String temp = map[x][y];
                while (directionIndex < 4) {
                    int nextX = x + directions[directionIndex][0];
                    int nextY = y + directions[directionIndex][1];
                    if(nextX < j || nextX >= map.length - j || nextY < j || nextY >= map[nextX].length - j) {
                        directionIndex++;
                    } else {
                        map[x][y] = map[nextX][nextY];
                        x = nextX;
                        y = nextY;
                    }
                }
                map[j+1][j] = temp;
            }
        }
 
        for(String[] row : map) {
            StringBuilder sb = new StringBuilder();
            for(String num : row) {
                sb.append(num + " ");
            }
            System.out.println(sb.toString().trim());
        }
    }
}
 
cs

알고리즘

  • 배열을 돌릴 그룹 수를 구한다.
  • 회전수만큼, 그룹수만큼, 배열을 하나씩 회전한다.
  • 각 그룹의 시작은 (0,0), (1,1), (2,2).. 이렇게 증가한다.
  • 그룹의 시작값을 임시로 가지고 있다가 배열을 한바퀴 전부 돌리고 난후, 마지막 요소에 첫 시작값을 넣어준다.
  • 다음 위치가 유효하지 않으면 다음 방향으로 진행한다. 다음 위치가 유효하면 요소를 변경한다
  • 요소를 변경할때 방향이 중요하다, 시계 반대 방향으로 돌려야하기 때문에 오른쪽으로 시작해서 다음 위치값을 현 위치에 넣는 방식으로 요소를 변경하며 배열을 돌린다.

'Algorithm' 카테고리의 다른 글

백준 - 11725 - 트리의 부모 찾기  (0) 2021.09.07
백준 - 4963 - 섬의 개수  (0) 2021.09.07
백준 - 2776 - 암기왕  (0) 2021.03.30
백준 - 10816 - 숫자 카드2  (0) 2021.03.29
프로그래머스 - 그래프 - 가장 먼 노드  (0) 2021.03.29