코딩 테스트/LeetCode
48. Rotate Image (이미지 회전) C#
포카리tea
2022. 11. 21. 13:42
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
n * n이미지를 나타내는 2D 가 주어지면 matrix이미지를 시계 방향으로 90도 회전합니다.
이미지를 제자리에서 회전해야 합니다. 즉, 입력 2D 매트릭스를 직접 수정해야 합니다. 다른 2D 매트릭스를 할당하고 회전하지 마십시오.

예시 1:
입력: matrix = [[1,2,3],[4,5,6],[7,8,9]]
출력: [[7,4,1],[8,5,2],[9,6,3]]

입력: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
출력: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
조건:
- n == matrix.length == matrix[i].length
- 1 <= n <= 20
- -1000 <= matrix[i][j] <= 1000
정답:
public class Solution {
public void Rotate(int[][] matrix)
{
int[][] temp = new int[matrix.Length][];
for (int i = 0; i < matrix.Length; i++)
{
temp[i] = new int[matrix.Length];
for (int j = 0; j < matrix.Length; j++)
{
temp[i][j] = matrix[i][j];
}
}
for (int i = 0; i < matrix.Length; i++)
{
for (int j = matrix.Length - 1; j >= 0; j--)
{
matrix[i][matrix.Length - 1 - j] = temp[j][i];
}
}
}
}
해설:
matrix 배열을 90도 돌릴때
[2][0] -> [0][0],
[1][0] -> [0][1],
[0][0] -> [0][2]
처럼 [i][matrix.Length - 1 - j]의 위치로 [j][i]가 옮겨진다는 규칙을 발견하여 그대로 풀어주었습니다.