按照顺时针的顺序,逐层遍历并打印N阶方阵
问题
逆时针打印矩阵,输入一个矩阵,按照从外向里逆时针的顺序打印出每一个数字。
输入: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 class MyReversePrint {
public static void main(String[] args) {
int[][] array =
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
ArrayList<Integer> printList = new ArrayList<Integer>();
printList = reversePrint(array);
printList.forEach(x -> System.out.print(x + " "));
}
public static ArrayList<Integer> reversePrint(int[][] array) {
// 二位数组(矩阵)的行数
int rows = array.length;
// 二位数组(矩阵)的列数
int columns = array[0].length;
ArrayList<Integer> myList = new ArrayList<Integer>();
// start表示圈数,从第0圈开始计数,没走一圈 圈数+1
int start = 0;
//让循环继续进行的条件是:矩阵的行数>当前的圈数×2且同时要满足矩阵的列数>当前的圈数×2.
while (rows > start * 2 && columns > start * 2) {
//记录每圈最后一行的下标
int endRow = rows - 1 - start;
//记录没圈最后一列的下标
int endColumn = columns - 1 - start;
//一圈圈逆序遍历数组中的元素,并插入到myList中
//1.从左到右
for (int i = start; i <= endColumn; i++)
myList.add(array[start][i]);
//2.从上到下
if (endRow > start) {
for (int i = start + 1; i <= endRow; i++)
myList.add(array[i][endColumn]);
}
//3.从右到左
if (endRow > start && endColumn > start) {
for (int i = endColumn - 1; i >= start; i--)
myList.add(array[endRow][i]);
}
//4.从下到上
if (endRow >= start + 2 && endColumn > start) {
for (int i = endRow - 1; i > start; i--)
myList.add(array[i][start]);
}
//圈数自增
start++;
}
return myList;
}
}