leetcode.com/problems/rotate-image/

 

Rotate Image - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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.

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

문제처럼 회전하는것이 - transpose한 후 y축에 대해 reverse한 것과 결과가 같다

class Solution {
	public void rotate(int[][] matrix) {
		int n = matrix.length;

		for (int i = 0; i < n; i++) {
			for (int j = i; j < n; j++) {
				int temp = matrix[j][i];
				matrix[j][i] = matrix[i][j];
				matrix[i][j] = temp;
			}
		}

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n / 2; j++) {
				int temp = matrix[i][j];
				matrix[i][j] = matrix[i][n - j - 1];
				matrix[i][n - j - 1] = temp;
			}
		}
	}
}

'개발자 > algorithm' 카테고리의 다른 글

백준 19279번 : 최대 힙 (java)  (0) 2021.01.12
LeetCode, Valid Parentheses (Java)  (0) 2021.01.09
LeetCode, Permutation (Java)  (0) 2021.01.07
LeetCode, Maximum Subarray (Java)  (0) 2021.01.06
LeetCode, Climbing Stairs (Java)  (0) 2021.01.05

+ Recent posts