Section titled Problem
Problem
Write a method to rotate an image by 90 degrees given an image represented by a NxN matrix, where each pixel in the image is 3 bytes (clockwise). Is it possible to do this in place?
For
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
the output should be
solution(a) =
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
Section titled Solution
Solution
The easiest way to rotate the matrix by 90 degrees clockwise is to implement the rotation in layers. Perform a circular rotation on each layer, moving the top edge to the right edget, the right edge to the bottom edge, the bottom edge to the left edge, and the left edge to the top edge.
How to perform four-way edge swap? Using copy between edge will require memory which actually unnecessary. To implement inplace rotation we only need 1 temporary and swapping by index instead of by values.
func solution(a [][]int) [][]int {
n:= len(a)
for layer:=0;layer <= n/2; layer++{
first, last:= layer, n-1-layer
for i:=first; i < last ; i++{
offset:= i-first
// save top
top:= a[first][i]
// left -> top
a[first][i] = a[last - offset][first]
// bottom -> left
a[last-offset][first] = a[last][last-offset]
// right -> bottom
a[last][last-offset] = a[i][last]
// top -> right
a[i][last] = top
}
}
return a
}
Section titled Dry%20Run
Dry Run
Input:
[[10,9,6,3,7],
[6,10,2,9,7],
[7,6,3,8,2],
[8,9,7,9,9],
[6,8,6,8,2]]
Result Rotate Layer 0
6 8 7 6 10
8 10 2 9 9
6 6 3 8 6
8 9 7 9 3
2 9 2 7 7
Result Rotate Layer 1
6 8 7 6 10
8 9 6 10 9
6 7 3 2 6
8 9 8 9 3
2 9 2 7 7
Result Rotate Layer 2
6 8 7 6 10
8 9 6 10 9
6 7 3 2 6
8 9 8 9 3
2 9 2 7 7