Skip to content

Instantly share code, notes, and snippets.

@kuanyingchou
Created November 9, 2015 02:21
Show Gist options
  • Save kuanyingchou/9231ca83f0362225b685 to your computer and use it in GitHub Desktop.
Save kuanyingchou/9231ca83f0362225b685 to your computer and use it in GitHub Desktop.
class Rotate {
public int[][] rotate(int[][] m, int s) {
if(m == null || m.length == 0) return m;
int w = m[0].length;
int h = m.length;
if(w == 1 || h == 1) return m;
for(int j=0; j<s; j++) {
int t1 = m[0][w-1];
for(int i=w-1; i>0; i--) {
m[0][i] = m[0][i-1];
}
//print(m);
int t2 = m[h-1][w-1];
for(int i=h-1; i>1; i--) {
m[i][w-1] = m[i-1][w-1];
}
m[1][w-1] = t1;
//print(m);
int t3 = m[h-1][0];
for(int i=0; i<w-2; i++) {
m[h-1][i] = m[h-1][i+1];
}
m[h-1][w-2]=t2;
//print(m);
for(int i=0; i<h-2; i++) {
m[i][0] = m[i+1][0];
}
m[h-2][0] = t3;
//print(m);
}
return m;
}
private static void print(int[][] m) {
for(int i=0; i<m.length; i++) {
System.out.print('[');
for(int j=0; j<m.length; j++) {
System.out.print(m[i][j]);
System.out.print(' ');
}
System.out.println(']');
}
System.out.println();
}
public static void main(String[] args) {
int[][] m = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 8, 0, 4 },
new int[] { 7, 6, 5 },
};
print(m);
new Rotate().rotate(m, 1);
print(m);
print(m);
new Rotate().rotate(m, 2);
print(m);
m = new int[][] {
new int[] { 1, 2 },
new int[] { 4, 3 },
};
print(m);
new Rotate().rotate(m, 1);
print(m);
m = new int[][] {
new int[] { 1 },
};
print(m);
new Rotate().rotate(m, 1);
print(m);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment