As stated, a matrix print clockwise. For example, the input matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Print out sequentially: 1 2. 4 8,121,615,141,395,671,110
Problem-solving ideas: Clockwise print, this matrix is thought of as a circle, a line regiment, starting at 1 draw, so roll up the line group, is not the case?
Is not that the famous rolling ball of algorithms Well! !
Yes, first printing 1234, and then roll over the matrix into a new matrix:
8 12 16
7 11 15
9 10 14
5 9 13
The second print 81216, and then roll over the matrix into a new matrix:
15 14 13
11 10 9
7 9 5
And so, oh friends, started working:
/**
* @description: 顺时针打印一个矩阵
* 例如输入矩阵:
* 1 2 3 4
* 5 6 7 8
* 9 10 11 12
* 13 14 15 16
* 打印出:1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
* @author: JandMin
* @create: 2019-05-24 09:26
**/
public class ClockwisePrintMatrix {
public static void main(String[] args) {
int n = 6;
int m = 7;
int[][] matrix = getMatrix(n ,m);
print(matrix);
System.out.println("==========================");
printClockwise(n,m,matrix);
}
/**
* 顺时针打印
* @param n 外层数组得长度
* @param m 里层数组得长度
* @param array 目标数组
*/
private static void printClockwise(int n,int m,int[][] array){
for(int j=0; j<m; j++){
print(array[0][j]);
}
int[][] newArray = reverse(n,m,array);
if(null == newArray || newArray.length <= 0){
return;
}
printClockwise(newArray.length,newArray[0].length,newArray);
}
/**
* 数组顺时针转90度,并且去掉第一个里层数组,变成一个新的数组
* @param n 外层数组得长度
* @param m 里层数组得长度
* @param array 目标数组
* @return
*/
private static int[][] reverse(int n,int m,int[][] array) {
if(n <=1){
return null;
}
int[][] newArray = new int[m][n-1];
int x = 0;
int y = 0;
for(int j=m-1; j>=0; j--){
for(int i=1; i<n; i++){
newArray[x][y++] = array[i][j];
}
x++;
y = 0;
}
return newArray;
}
/**
* 从1开始获取二维数组
* @param n 外层数组得长度
* @param m 里层数组得长度
* @return
*/
public static int[][] getMatrix(int n,int m){
int[][] matrix = new int[n][m];
int k = 1;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++) {
matrix[i][j] = k++;
}
}
return matrix;
}
private static void print(int[][] array){
for(int i=0; i<array.length; i++){
for(int j=0; j<array[i].length; j++){
print(array[i][j]);
}
System.out.println();
}
}
private static void print(int num){
System.out.print(num);
if(num < 10){
System.out.print(" ");
} else {
System.out.print(" ");
}
}
}
Execution results are as follows:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
36 37 38 39 40 41 42
==========================
1 2 3 4 5 6 7 14 21 28 35 42 41 40 39 38 37 36 29 22 15 8 9 10 11 12 13 20 27 34 33 32 31 30 23 16 17 18 19 26 25 24
Of course, there are many solution would be more simple, welcome Daniel pointed out the error, or a comment posted more solution, the exchange! !
====== ======== method than problems