标签:array new public matrix 顺序 off 顺时针 ++ 个数
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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.
这个。。我没找什么特别的方法,就用思路最清晰的方法,用循环来做,并且几个判断条件都要带=,不然结果会出错。
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<>();
int EndX = matrix.length - 1;
int EndY = matrix[0].length - 1;
int StartX = 0;
int StartY = 0;
int x = StartX, y = StartY;
while (StartX <= EndX && StartY <= EndY) {
if (StartX <= EndX) {
while (y <= EndY) {
list.add(matrix[x][y]);
y++;
}
y--;
StartX++;
x = StartX;
}
if (StartY <= EndY) {
while (x <= EndX) {
list.add(matrix[x][y]);
x++;
}
x--;
EndY--;
y = EndY;
}
if (StartX <= EndX) {
while (y >= StartY) {
list.add(matrix[x][y]);
y--;
}
y++;
EndX--;
x = EndX;
}
if (StartY <= EndY) {
while (x >= StartX) {
list.add(matrix[x][y]);
x--;
}
x++;
StartY++;
y = StartY;
}
}
return list;
}
标签:array new public matrix 顺序 off 顺时针 ++ 个数
原文地址:https://www.cnblogs.com/blogxjc/p/12382681.html