Rotate a Matrix by 90 Degrees (Clockwise)

medium Matrix (2D arrays)

Problem

Read a matrix with r rows and c columns. Rotate it by 90 degrees clockwise and print the result (it has c rows and r columns).

Constraints

  • 1 <= r, c <= 100

Examples

Input

2 3
1 2 3
4 5 6

Output

4 1
5 2
6 3

Solutions

Best approachTime O(r * c)Space O(r * c)

Rotating clockwise means: the first column (read from the bottom to the top) becomes the first row. It equals a transpose followed by reversing every row.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process a matrix.
 * Input   : r and c, then r rows of c integers.
 * Output  : The rotated matrix.
 * Approach: Rotation = transpose + reverse rows.
 * Time    : O(r * c)
 * Space   : O(r * c)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(int[][] m) {
        int rows = m.length;
        int cols = m[0].length;
        String[] lines = new String[cols];

        // Step 1: The new row j is the old column j, read from the bottom to the top.
        for (int j = 0; j < cols; j++) {
            StringBuilder line = new StringBuilder();

            // Step 2: Go through the old rows from the last to the first.
            for (int i = rows - 1; i >= 0; i--) {
                if (i < rows - 1) {
                    line.append(" ");
                }
                line.append(m[i][j]);
            }
            lines[j] = line.toString();
        }
        return lines;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int rows = scanner.nextInt();
        int cols = scanner.nextInt();
        int[][] m = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                m[i][j] = scanner.nextInt();
            }
        }
        System.out.println(String.join("\n", solve(m)));
    }
}
Hints (1)
  1. Which old column becomes the first row?