给定一个整型矩阵matrix:
1 2 3 4
5 6 7 8
9 10 11 12
1.按转圈的方式打印:
打印结果:1 2 3 4 8 12 11 10 9 5 6 7
2.按顺时针旋转方式打印::
打印结果为:
9 5 1
10 6 2
11 7 3
12 8 4
注意: 此方式适用于任意数组
思路:
public class CircleMatrix {
//输出数组
public static void printMatrix(int[][] arr){
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[i].length;j++) {
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
}
//将数组顺时针旋转
public static int[][] rotateMatrix(int[][] arr){
int[][] brr=new int[arr[0].length][arr.length];
int count=0;
while(count<(arr.length+1)/2) {
//上
for (int column = count; column < arr[count].length-count; column++) { //count:列
brr[column][brr[count].length - 1 - count]=arr[count][column];
}
//左
for (int row = count + 1; row < arr.length-count; row++) {
brr[count][brr[count].length - 1 - row] = arr[row][count];
}
//下
for (int column = count + 1; column < arr[count].length-count; column++) {
brr[column][count] = arr[brr[count].length - 1 - count][column];
}
//右
for (int row = arr.length - 1 - 1 - count; row > count; row--) {
brr[brr.length - 1-count][brr[count].length-1-row] = arr[row][arr[count].length - 1 - count];
}
count++;
}
return brr;
}
//转圈打印二维数组
public static void circleMatrix(int[][] arr){
int count=0;
while(count<(arr.length+1)/2){
//上
for(int column=count;column<arr[count].length-count;column++){ //column: 列
System.out.print(arr[count][column]+" ");
}
//右
for(int row=count+1;row<arr.length-count;row++){ //row:行
System.out.print(arr[row][arr[count].length-1-count]+" ");
}
//下
for(int column=arr[count].length-1-1-count;column>count;column--){ //arr[count].length-1开始-1-count
System.out.print(arr[arr.length-1-count][column]+" ");
}
//左
for(int row=arr.length-1-1-count+1;row>count;row--){
System.out.print(arr[row][count]+" ");
}
count++;
}
}
public static void main(String[] args) {
int[][] arr={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
printMatrix(arr);
System.out.println("转圈打印结果为:");
circleMatrix(arr);
System.out.println();
System.out.println("顺时针旋转打印结果为:");
int[][] brr=rotateMatrix(arr);
printMatrix(brr);
}
}
运行结果: