https://www.hackerrank.com/challenges/matrix-rotation-algo
For the first try, I thought for writing the algorithm such that it would rotate the matrix once in anti-clockwise direction and then I would create a loop which would the run the said logic R times! This approach produces the correct outputs but the run time of the code is much much higher for large inputs.
http://code.antonio081014.com/2011/11/interview-problem-rotate-matrix.html
* Given an image represented by an NxN matrix,
* where each pixel in the image is 4 bytes,
* write a method to rotate the image by 90 degrees.
public static void rotate(int[][] matrix, int n) {
for (int i = 0; i < n / 2; i++) {
int left = i;
int right = n - 1 - i;
for (int j = left; j < right; j++) {
int offset = j - left;
// save the top element;
int tmp = matrix[left][left + offset];
// right -> top;
matrix[left][left + offset] = matrix[left + offset][right];
// bottom -> right;
matrix[left + offset][right] = matrix[right][right - offset];
// left -> bottom;
matrix[right][right - offset] = matrix[right - offset][left];
// top -> left;
matrix[right - offset][left] = tmp;
}
}
}
https://github.com/careercup/CtCI-6th-Edition/blob/master/Java/Ch%2001.%20Arrays%20and%20Strings/Q1_07_Rotate_Matrix/Question.java
You are given a 2D matrix, a, of dimension MxN and a positive integer R. You have to rotate the matrix Rtimes and print the resultant matrix. Rotation should be in anti-clockwise direction.
Rotation of a 4x5 matrix is represented by the following figure. Note that in one rotation, you have to shift elements by one step only (refer sample tests for more clarity).
It is guaranteed that the minimum of M and N will be even.
http://techcmxiv.blogspot.in/2015/12/matrix-rotation.html?view=magazine
//Rotate - Definition
void rotate() {
long limit = M>N?N/2:M/2;
for(long i=0; i<limit; i++) {
for(long r=0; r<R%(2*(M+N-4*i-2)); r++)
rotate(i);
}
}
void rotate(long diag) {
long col, row, temp = matrix[diag][diag];
row = col = diag;
for(; col<N-diag-1; col++) matrix[row][col] = matrix[row][col+1];
for(; row<M-diag-1; row++) matrix[row][col] = matrix[row+1][col];
for(; col>diag; col--) matrix[row][col] = matrix[row][col-1];
for(; row>diag; row--) matrix[row][col] = matrix[row-1][col];
matrix[diag+1][diag] = temp;
}
http://www.martinkysel.com/hackerrank-matrix-rotation-solution/
Approach #2
For this successful try, I browsed the discussion section of problem and found out that I have to normalize the rotation for each of the rectangles. Check out the accepted code here.
This code was accepted because of its relatively low time complexity, let us assume that
Ri = # of rotations for ith rectangle of the matrix
Ri = R%(2*(M+N-4*i-2) where M = # of Rows, N = # of Cols & R = # of rotations.
Then, the run time would be (T0*R0 + T1*R1 + T2*R2 + .... + Tlimit * Rlimit)
Now, Ri is calculated as R%(# of elements in the rectangle or the length of the rectangle)
https://gist.github.com/cmxiv/6ee0f6b37e4ab36ac947This code was accepted because of its relatively low time complexity, let us assume that
Ri = # of rotations for ith rectangle of the matrix
Ri = R%(2*(M+N-4*i-2) where M = # of Rows, N = # of Cols & R = # of rotations.
Then, the run time would be (T0*R0 + T1*R1 + T2*R2 + .... + Tlimit * Rlimit)
Now, Ri is calculated as R%(# of elements in the rectangle or the length of the rectangle)
//Rotate - Definition
void rotate() {
long limit = M>N?N/2:M/2;
for(long i=0; i<limit; i++) {
for(long r=0; r<R%(2*(M+N-4*i-2)); r++)
rotate(i);
}
}
void rotate(long diag) {
long col, row, temp = matrix[diag][diag];
row = col = diag;
for(; col<N-diag-1; col++) matrix[row][col] = matrix[row][col+1];
for(; row<M-diag-1; row++) matrix[row][col] = matrix[row+1][col];
for(; col>diag; col--) matrix[row][col] = matrix[row][col-1];
for(; row>diag; row--) matrix[row][col] = matrix[row-1][col];
matrix[diag+1][diag] = temp;
}
http://www.martinkysel.com/hackerrank-matrix-rotation-solution/
I first extract layers, to simplify the logic. Then, I rotate the layers similarly to the Codility Rotation challenge.
def reverse(arr, i, j):
for idx in xrange((j - i + 1) / 2):
arr[i + idx], arr[j - idx] = arr[j - idx], arr[i + idx]
def rotateList(A, K):
# performs a right rotation
# K needs to be adjusted to len(A) - K for left rotation
l = len(A)
K %= len(A)
reverse(A, l - K, l - 1)
reverse(A, 0, l - K - 1)
reverse(A, 0, l - 1)
return A
def rotateLayers(N, M, R, layers):
for layer in layers:
rotateList(layer, len(layer) - R)
def rotateMatrix(M, N, R, mat):
# generate a list of layers
l = int(min(N, M) // 2)
layers = [[] for _ in range(l)]
for level in xrange(l):
top = (N - 1) - 2 * level
side = (M - 1) - 2 * level
for i in range(top): # right
layers[level].append(mat[level][level + i])
for j in range(side): # down
layers[level].append(mat[level + j][level + top])
for i in range(top): # left
layers[level].append(mat[level + side][level + top - i])
for j in range(side): # up
layers[level].append(mat[level + side - j][level])
# rotate each layer
rotateLayers(N, M, R, layers)
# fill the layers back in
for level in range(l):
top = (N - 1) - 2 * level
side = (M - 1) - 2 * level
for i in xrange(top):
mat[level][level + i] = layers[level].pop(0) # right
for j in range(side):
mat[level + j][level + top] = layers[level].pop(0) # down
for i in range(top):
mat[level + side][level + top - i] = layers[level].pop(0) # left
for j in range(side):
mat[level + side - j][level] = layers[level].pop(0) # up
def main():
M, N, R = map(int, raw_input().split())
mat = []
for i in range(M):
mat.append(list(map(int, raw_input().split())))
rotateMatrix(M, N, R, mat)
# print the rotated matrix
for row in range(M):
for col in range(N):
print mat[row][col],
print
For the first try, I thought for writing the algorithm such that it would rotate the matrix once in anti-clockwise direction and then I would create a loop which would the run the said logic R times! This approach produces the correct outputs but the run time of the code is much much higher for large inputs.
int main() {
cin>>M>>N>>R;
initMatrix();
inputMatrix();
for(long r=0; r<R; r++) rotate();
outputMatrix();
return 0;
}
//Matrix functions - Definition
void initMatrix() {
matrix = new long* [M];
for(long i=0; i<M; i++)
matrix[i] = new long[N];
}
void inputMatrix() {
for(long i=0; i<M; i++)
for(long j=0; j<N; j++)
cin>>matrix[i][j];
}
//Rotate - Definition
void rotate() {
long limit = M>N?N/2:M/2;
for(long i=0; i<limit; i++) rotate(i);
}
void rotate(long diag) {
long col, row, temp = matrix[diag][diag];
row = col = diag;
for(; col<N-diag-1; col++) matrix[row][col] = matrix[row][col+1];
for(; row<M-diag-1; row++) matrix[row][col] = matrix[row+1][col];
for(; col>diag; col--) matrix[row][col] = matrix[row][col-1];
for(; row>diag; row--) matrix[row][col] = matrix[row-1][col];
matrix[diag+1][diag] = temp;
}
* Given an image represented by an NxN matrix,
* where each pixel in the image is 4 bytes,
* write a method to rotate the image by 90 degrees.
public static void rotate(int[][] matrix, int n) {
for (int i = 0; i < n / 2; i++) {
int left = i;
int right = n - 1 - i;
for (int j = left; j < right; j++) {
int offset = j - left;
// save the top element;
int tmp = matrix[left][left + offset];
// right -> top;
matrix[left][left + offset] = matrix[left + offset][right];
// bottom -> right;
matrix[left + offset][right] = matrix[right][right - offset];
// left -> bottom;
matrix[right][right - offset] = matrix[right - offset][left];
// top -> left;
matrix[right - offset][left] = tmp;
}
}
}
https://github.com/careercup/CtCI-6th-Edition/blob/master/Java/Ch%2001.%20Arrays%20and%20Strings/Q1_07_Rotate_Matrix/Question.java
Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
public static boolean rotate(int[][] matrix) {
if (matrix.length == 0 || matrix.length != matrix[0].length) return false; // Not a square
int n = matrix.length;
for (int layer = 0; layer < n / 2; layer++) {
int first = layer;
int last = n - 1 - layer;
for(int i = first; i < last; i++) {
int offset = i - first;
int top = matrix[first][i]; // save top
// left -> top
matrix[first][i] = matrix[last-offset][first];
// bottom -> left
matrix[last-offset][first] = matrix[last][last - offset];
// right -> bottom
matrix[last][last - offset] = matrix[i][last];
// top -> right
matrix[i][last] = top; // right <- saved top
}
}
return true;
}