1 | 2 | 3 | 4 |
14 | 15 | 16 | 5 |
13 | 30 | 17 | 6 |
12 | 19 | 18 | 7 |
11 | 10 | 9 | 8 |
public class RotateMatrix {
private int[][] result;
private int maxNum;
public RotateMatrix(int m, int n) {
this.result = new int[m][n];
this.maxNum = m * n;
}
public static void main(String[] args) {
int m = 5;
int n = 4;
new RotateMatrix(m, n).generateRotate(m, 0, n, 0, 1);
}
public void generateRotate(int currentMLength, int currentM, int currentNLength, int currentN, int currentNum) {
for(int i = currentN ; i < currentNLength ; i ++) {
result[currentM][i] = currentNum;
currentNum ++;
}
for(int i = currentM + 1 ; i < currentMLength - 1 ; i ++) {
result[i][currentNLength - 1] = currentNum;
currentNum ++;
}
for(int i = currentNLength - 1 ; i > currentN ; i --) {
result[currentMLength - 1][i] = currentNum;
currentNum ++;
}
for(int i = currentMLength - 1 ; i > currentM ; i --) {
result[i][currentN] = currentNum;
currentNum ++;
}
currentM ++;
currentN ++;
currentMLength --;
currentNLength --;
if(currentNum < maxNum) {
generateRotate(currentMLength, currentM, currentNLength, currentN, currentNum);
}
}
}