转圈打印矩阵
题目:
思路:
本题难点:由于是整型矩阵,所以存在5*5,4*5,4*6,这种,可能出现还剩下一列或者一行或者单个的情况。
代码示例:
import java.util.Arrays;
public class Solution2 {
public static void main(String[] args) {
int len = 7, higt = 10;
int[][] A = new int[higt][len];
for (int i = 0; i < higt; i++) {
for (int j = 0; j < len; j++) {
A[i][j] = j + 1 + i * len;
System.out.print(A[i][j] + "\t");
}
System.out.println();
}
System.out.println(Arrays.toString(printMatrix(A)));
}
/**
* @param matrix int整型二维数组 the matrix
* @return int整型一维数组
*/
public static int[] printMatrix(int[][] matrix) {
int length = matrix[0].length, high = matrix.length;
int num = length * high;
int[] result = new int[num];
int upper = 0, lower = high - 1, left = 0, right = length - 1;
int index = 0;
while (upper < lower && left < right) {
for (int i = left; i <= right; i++) {
result[index++] = matrix[upper][i];
}
upper++;
for (int i = upper; i <= lower; i++) {
result[index++] = matrix[i][right];
}
right--;
for (int i = right; i >= left; i--) {
result[index++] = matrix[lower][i];
}
lower--;
for (int i = lower; i >= upper; i--) {
result[index++] = matrix[i][left];
}
left++;
}
//由于是整型矩阵,所以存在5*5,4*5,4*6,这种,可能出现还剩下一列或者一行或者单个的情况
if (left == right && upper < lower) {
for (int i = upper; i <= lower; i++) result[index++] = matrix[i][left];
} else if (upper == lower && left < right) {
for (int i = left; i <= right; i++) result[index++] = matrix[upper][i];
} else if (left == right && upper == lower) {
result[index] = matrix[upper][left];
}
return result;
}
}