Rotate Image
Turn a square grid of numbers a quarter turn clockwise, changing the grid itself instead of building a new one.
Given a square grid of integers, matrixmatrix
Example 1
Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Example 2
Output: [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]
The Idea
Turn your phone sideways while a photo is open, and the photo turns a quarter of the way round with it. On the screen, a photo is a grid of tiny coloured dots, and a program keeps those dots as a grid of numbers. Rotating the image means moving every number to its place in the turned grid.
Take Example 1, where row 0 holds 1, 2 and 3. After the turn, those three numbers stand in the last column, col 2, reading down: 1 in row 0, 2 in row 1 and 3 in row 2. The bottom row, 7, 8, 9, moves into col 0, so the new row 0 reads 7, 4, 1. In general, the number at row r, col c moves to row c, col n - 1 - r.
With a second grid, that rule is all you need. Here, though, the answer goes into the same grid. Writing 1 into row 0, col 2 would wipe out the 3 that sits there before the 3 has moved anywhere. So how can every number move without losing any of them?
Swapping two numbers never loses either one, so the turn has to be built out of swaps. Two flips do it. First, swap each number with its mirror image across the diagonal that runs from the top left corner to the bottom right, through 1, 5 and 9. This flip is called a transpose: it turns row 0 into col 0, row 1 into col 1, and so on. Then reverse each row.
The picture shows Example 1 in three stages. Follow the orange 2: it starts at row 0, col 1. The transpose moves it to row 1, col 0, and reversing row 1 moves it on to row 1, col 2, exactly where the rule above sends it. The teal cells, 1, 5 and 9, sit on the diagonal and stay put in the transpose.
The grid labelled "after reversing each row" reads 7, 4, 1, then 8, 5, 2, then 9, 6, 3, which is the expected output. Each of the two flips is only a series of swaps, so neither needs a second grid.
Solution Approach
A spare grid gives a simple answer that the problem does not allow, and the in-place version needs three choices: why the two flips equal one turn, which cells the transpose swaps, and how each row is reversed.
Rotating with a spare grid
What is the most direct way? Make a new n by n grid, copy each number from row r, col c to row c, col n - 1 - r, and then copy the new grid back into matrix
Why two flips make a quarter turn
Can we be sure the two flips put every number where the rule says, and not just the 2? The transpose sends the number at row r, col c to row c, col r. Reversing row c keeps the number in that row and moves it from col r to col n - 1 - r. Together that is row c, col n - 1 - r, the rotation rule, for every cell.
Swapping only above the diagonal
Which cells should the transpose visit? If it visits every cell, the pair at row 0, col 1 and row 1, col 0 is swapped twice, once from each side. The second swap undoes the first, and the grid ends up as it started.
So in row r, the transpose visits only the columns from r + 1 on, which are the cells above the diagonal. Each pair is then swapped once, and the diagonal cells, which would only swap with themselves, are skipped.
Reversing a row in place
How is one row reversed without a spare row? Put one marker, leftright
Java Solution
The method rotate
- First, store the size of the grid in
, fromn .matrix.length - Transpose the grid with two loops, one inside the other. The outer loop moves
down the rows. For eachr , the inner loop movesr fromc to the last column and swapsr + 1 withmatrix[r][c] , holding one of them in a temporary variablematrix[c][r] .t - Then reverse each row. A loop takes each
ofrow in turn. Inside it,matrix starts at 0 andleft atright , and they swap their numbers and move toward each other whilen - 1 is less thanleft .right - The method returns nothing, because the turned grid is now in
itself.matrix
A small helper, rotateAndPrintmain
import java.util.Arrays;
public class RotateImage {
public static void rotate(int[][] matrix) {
int n = matrix.length;
for (int r = 0; r < n; r++) { // 1. transpose
for (int c = r + 1; c < n; c++) { // only cells above the diagonal
int t = matrix[r][c];
matrix[r][c] = matrix[c][r];
matrix[c][r] = t;
}
}
for (int[] row : matrix) { // 2. reverse each row
for (int left = 0, right = n - 1; left < right; left++, right--) {
int t = row[left];
row[left] = row[right];
row[right] = t;
}
}
}
static void rotateAndPrint(String label, int[][] matrix) {
rotate(matrix);
System.out.println(label + ":");
for (int[] row : matrix) {
System.out.println(" " + Arrays.toString(row));
}
}
public static void main(String[] args) {
rotateAndPrint("Example 1", new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
int[][] example2 = {{5, 1, 9, 11}, {2, 4, 8, 10}, {13, 3, 6, 7}, {15, 14, 12, 16}};
rotateAndPrint("Example 2", example2);
rotateAndPrint("2 x 2", new int[][] {{1, 2}, {3, 4}});
rotateAndPrint("1 x 1", new int[][] {{1}});
int[][] start = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] turned = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int turn = 0; turn < 4; turn++) {
rotate(turned);
}
System.out.println("Four turns give back the start: " + Arrays.deepEquals(start, turned));
}
}
Running it prints:
Example 1:
[7, 4, 1]
[8, 5, 2]
[9, 6, 3]
Example 2:
[15, 13, 2, 5]
[14, 3, 4, 1]
[12, 6, 8, 9]
[16, 7, 10, 11]
2 x 2:
[3, 1]
[4, 2]
1 x 1:
[1]
Four turns give back the start: true
Under "Example 1", the rows [7, 4, 1][8, 5, 2][9, 6, 3][[1, 2], [3, 4]][3, 1][4, 2]
The 1 x 1 grid prints [1]true[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Starting the inner transpose loop at c = 0r + 1[[1, 2, 3], [4, 5, 6], [7, 8, 9]][[3, 2, 1], [6, 5, 4], [9, 8, 7]]
Complexity
Each flip handles every cell of the n by n grid at most once, and the extra storage is a few loop counters plus the temporary t
- Time: O(n2), because the transpose swaps each of the n(n - 1) / 2 pairs across the diagonal once, and the row reversal makes about n / 2 swaps in each of the n rows.
- Space: O(1), because both flips swap numbers inside
itself and need only the variablematrix , while the spare-grid way would need room for n2 more numbers.t
The first flip on its own is the subject of