2019-05-23转圈打印矩阵
2019-05-23 本文已影响0人
咣超
package 练习题;
public class Matrix1 { // 转圈打印矩阵一个框一个框的打印
public static void printMatrix(int[][] arr) {
int a=0;
int b=0;
int c=arr.length-1;
int d=arr[0].length-1;
while(a <= c && b <= d) { // 假如只给你一列数或一行数是边界的处理
printProcess(arr, a++, b++, c--, d--);
}
}
public static void printProcess(int[][] arr, int a, int b, int c, int d) {
int a1 = a;
int b1 = b;
if(a1 == c) { // 只给一列数时
while(b1 <= d) {
System.out.println(arr[a1][b1++] + " ");
}
}else if(b1 == d){ // 一行数时
while(a1 <= c) {
System.out.println(arr[a1][b1]+ " ");
a1++;
}
}else {
while(b1 != d) {
// 这四个while和上面两个的区别是这里每一行或者每一列的最后的点总是由下一个while来打印
// 如果换成<=的话每行每列的最后的点就打不出来了
System.out.println(arr[a][b1]+ " ");
b1++;
}
while(a1 != c) {
System.out.println(arr[a1][d]+ " ");
a1++;
}
while(b1 != b) {
System.out.println(arr[c][b1]+ " ");
b1--;
}
while(a1 != a) {
System.out.println(arr[a1][b]+ " ");
a1--;
}
}
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{1, 2, 3, 4},
{7, 8, 9, 0}
};
printMatrix(matrix);
}
}