#codingexercise
Rotate a n x n matrix by 90 degrees:
Rotate a n x n matrix by 90 degrees:
static void matrixRotate(ref List<List<int>> A, int r0, int c0, int rt, int ct)
{
if (r0 >= rt) return;
if (c0 >= ct) return;
var top = new int[ct-c0+1];
int count = 0;
for (int j = 0; j <= ct-c0; j++){
top[count] = A[0][j];
count++;
}
count--;
for (int j = ct; j >= c0; j--)
A[c0][j] = A[ct-j][0];
for (int i = r0; i <= rt; i++)
A[i][c0] = A[rt][i];
for (int j = c0; j <= ct; j++)
A[rt][j] = A[ct-j][ct];
for (int i = rt; i >= r0; i--) {
A[i][ct] = top[count];
count--;
}
matrixRotate(ref A, r0+1, c0+1, rt-1, ct-1);
}
// Before:
1 2 3
4 5 6
7 8 9
// After:
7 4 1
8 5 2
9 6 3
// Before
1 2
3 4
// After
3 1
4 2
Some others: https://ideone.com/IdbbBp
https://ideone.com/690TtN
// Before:
1 2 3
4 5 6
7 8 9
// After:
7 4 1
8 5 2
9 6 3
// Before
1 2
3 4
// After
3 1
4 2
Some others: https://ideone.com/IdbbBp
https://ideone.com/690TtN
No comments:
Post a Comment