Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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
Archives
Today
Total
관리 메뉴

Life Engineering

[BOJ 16926] 배열 돌리기 1(Java) 본문

Problem Solving

[BOJ 16926] 배열 돌리기 1(Java)

흑개 2022. 2. 11. 14:24

https://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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class P16926_1 {
	static int N, M, R;
	static int[][] graph;
	public static void main(String[] args) throws IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer(br.readLine(), " ");
		N=Integer.parseInt(st.nextToken());
		M=Integer.parseInt(st.nextToken());
		R=Integer.parseInt(st.nextToken());
		graph=new int[N][M];
		for (int i=0; i<N; i++) {
			 st=new StringTokenizer(br.readLine(), " ");
			 for (int j=0; j<M; j++) {
				 graph[i][j]=Integer.parseInt(st.nextToken());
			 }
		}
		for (int i=0; i<R; i++) {
			rotate();
		}
		for (int i=0; i<N; i++) {
			for (int j=0; j<M; j++) {
				System.out.print(graph[i][j]+" ");
			}
			System.out.println();
		}

	}
	private static void rotate() {
		int cnt=Math.min(N, M)/2;
		for (int i=0; i<cnt; i++) {
			int y=i, x=i;
			int temp=graph[y][x];
			int Mmax=(M-i)-1;
			int Nmax=(N-i)-1;
			while (x<Mmax) {
				graph[y][x]=graph[y][x+1];
				x++;
			}
			while (y<Nmax) {
				graph[y][x]=graph[y+1][x];
				y++;
			}
			while (x>i) {
				graph[y][x]=graph[y][x-1];
				x--;
			}
			while (y>i) {
				graph[y][x]=graph[y-1][x];
				y--;
			}
			graph[i+1][i]=temp;
		}
	}
}

 

여기서 중요한 포인트는 돌릴 직사각형의 개수를 구하는 것이다. (i번째 직사각형)

돌릴 직사각형의 개수는 min(N, M)/2 로 구해주고, 각 직사각형 당 시계방향으로 값을 바꿔준다.

여기서 주의할 점은 경계 설정이다. 경계를 [i, N-i), [j, M-i) 로 설정해 경계를 만날 때마다 방향을 바꿔주도록 한다.