输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
提示:编写代码时,可以先不考虑单行或者单列的情况,等编写完成后,再假设此时是单行(列),然后走一遍程序,根据哪里会出问题来修改解决单行(列)情况。
- 非递归版
import java.util.ArrayList;
public class s {
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<>();
int index = 0; //圈数
int row = matrix.length;
int col = matrix[0].length;
int left = 0;
int right = col - 1;
int top = 0;
int bottom = row - 1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++) {
list.add(matrix[top][i]);
}
for (int i = top + 1; i <= bottom; i++) {
list.add(matrix[i][right]);
}
if (top != bottom) {
for (int i = right - 1; i >= left; i--) {
list.add(matrix[bottom][i]);
}
}
if (left != right) {
for (int i = bottom - 1; i >= top + 1; i--) {
list.add(matrix[i][left]);
}
}
left++;
right--;
top++;
bottom--;
index++;
}
System.out.println(index);
return list;
}
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}};
s t = new s();
ArrayList<Integer> res = t.printMatrix(matrix);
System.out.println(res); //其中圈数index为3
}
}
- 递归版
public class T_19_PrintMatrix {
public ArrayList<Integer> printMatrix(int[][] matrix) {
int tR = 0;
int tC = 0;
int dR = matrix.length - 1;
int dC = matrix[0].length - 1;
ArrayList<Integer> list = new ArrayList<>();
while (tR <= dR && tC <= dC) {
list = printEdge(matrix, tR++, tC++, dR--, dC--, list);
}
return list;
}
public static ArrayList<Integer> printEdge(int[][] m, int tR, int tC, int dR, int dC, ArrayList list) {
if (tR == dR) {
for (int i = tC; i <= dC; i++) {
list.add(m[tR][i]);
}
} else if (tC == dC) {
for (int i = tR; i <= dR; i++) {
list.add(m[i][tC]);
}
} else {
int curC = tC;
int curR = tR;
while (curC != dC) {
list.add(m[tR][curC]);
curC++;
}
while (curR != dR) {
list.add(m[curR][dC]);
curR++;
}
while (curC != tC) {
list.add(m[dR][curC]);
curC--;
}
while (curR != tR) {
list.add(m[curR][tC]);
curR--;
}
}
return list;
}
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12},
{13, 14, 15, 16}};
T_19_PrintMatrix t = new T_19_PrintMatrix();
ArrayList<Integer> res = t.printMatrix(matrix);
System.out.println(res);
}
}
本文介绍了一种矩阵螺旋打印算法,包括非递归和递归两种实现方式,详细展示了如何按顺时针方向从外向内打印矩阵中的数字,适用于4X4及任意大小的矩阵。
1478

被折叠的 条评论
为什么被折叠?



