顺时针打印3*3矩阵

import java.util.ArrayList;
public class Mytest {
//剑指OFFer 顺时针打印n*m矩阵
//思路 模拟过程 以顺时针顺序打印几层 取决于行数与列数中最小的那一个 两层构成一圈 两个之中最小的那个除以2
//
public static void main(String[] args) {
String[][] a= new String[][]{{“001”, “002”, “003”}, {“111”, “222”,“333” },{“011”,“022”, “033”}};
System.out.println(new Mytest().printMatrix(a));
}
public ArrayList printMatrix(String[][] matrix) {
ArrayList list = new ArrayList<>();
int m = matrix.length;
if (m == 0) {
return list;}
int n = matrix[0].length;
int c1 = 0;
int c2 = n - 1;
int r1 = 0;
int r2 = m - 1;
int times = Math.min(m, n) % 2 == 0 ? Math.min(m, n) / 2 : Math.min(m, n) / 2 + 1;
for (int i = 0; i < times; i++) {
for (int c = c1; c <= c2; c++) list.add(matrix[r1][c]);
for (int r = r1 + 1; r <= r2; r++) list.add(matrix[r][c2]);
if (r1 < r2 && c1 < c2) {
for (int c = c2 - 1; c > c1; c–) list.add(matrix[r2][c]);
for (int r = r2; r > r1; r–) list.add(matrix[r][c1]);
}
r1++;
r2–;
c1++;
c2–;
}
return list;
}

}

posted @ 2021-05-27 08:53  穆雄雄  阅读(127)  评论(0编辑  收藏  举报