Rotate Matrix | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

Rotate Matrix by 90 degrees

Example 1

package com.test;

import java.util.Arrays;

/**
 * @author code.factory
 *
 */
public class CodeFactory {
	public static void main(String[] args) {
		int arr[][] = {{1, 2, 3},
				{4, 5, 6},
				{7, 8, 9}};
		System.out.println(Arrays.deepToString(rotateArr(arr)));
	}

	private static int[][] rotateArr(int[][] arr) {
		int[][] newArr = new int[arr[0].length][arr.length];
		for(int i=0; i<arr[0].length; i++) {
			for(int j=0; j<arr.length; j++) {
				newArr[i][j] = arr[arr.length-1 - j][i];
			}
		}
		return newArr;
	}
}

Output:

Input:
1 2 3
4 5 6
7 8 9

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


Input:
1 2
4 5
7 8

Output:
[[7, 4, 1], 
[8, 5, 2]]


Input:
1
2
3

Output:
[[3, 2, 1]]

Example 2 – Swap number

package com.test;

import java.util.Arrays;

/**
 * @author code.factory
 *
 */
public class CodeFactory {
	public static void main(String[] args) throws InterruptedException {
		int arr[][] = {{1, 2, 3, 4},
					{5, 6, 7, 8},
					{9, 10, 11, 12},
					{13, 14, 15, 16}};
		rotateArr(arr);
	}

	private static void rotateArr(int[][] arr) {
		int L = arr.length - 1;
		for(int i=0; i<arr.length/2; i++) {
			for(int j=i; j<arr.length - i - 1; j++) {
				int temp = arr[i][j];
				arr[i][j] = arr[L-j][i];
				arr[L-j][i] = arr[L-i][L-j];
				arr[L-i][L-j] = arr[j][L-i];
				arr[j][L-i] = temp;
			}
		}
		System.out.println(Arrays.deepToString(arr));
	}
}

Output:

[[13, 9, 5, 1], 
[14, 10, 6, 2], 
[15, 11, 7, 3], 
[16, 12, 8, 4]]

Leave a comment